Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is subclassing not allowed for many of the SWT Controls?

Tags:

java

swt

I often find myself wanting to do it. It can be very useful when you want to store some useful information or extra states.

So my question is, is there a very good/strong reason why this is forbidden?

Thanks

EDIT: Thanks a lot for all these answers. So it sounds like there's no right-or-wrong answer to this.

Assuming I accept the fact that these classes are not to be subclassed, what's the point of not marking a Control class final, but prohibiting subclassing - effectively demoting the exception/error from compile-time to run-time?

EDIT^2: See my own answer to this: apparently, these classes are overrideable, but requires explicit acknowledgement by the overrider.

Thanks

like image 228
RAY Avatar asked Nov 24 '10 09:11

RAY


2 Answers

It doesn't look like anybody mentioned this in any of the answers, but SWT does provide an overrideable checkSubclass() method; precisely where the Unextendable exception is thrown. Override the method to a no-op and effectively make extending legal. I guess to leave this option open is ultimately the reason that the class is not made final and the extension error not made compile-time instead of run-time.

Example:

@Override
protected void checkSubclass() {
    //  allow subclass
    System.out.println("info   : checking menu subclass");
}
like image 72
RAY Avatar answered Sep 28 '22 03:09

RAY


Designing components for inheritance is hard, and can limit future implementation changes (certainly if you leave some methods overridable, and call them from other methods). Prohibiting subclassing restricts users, but means it's easier to write robust code.

This follows Josh Bloch's suggestion of "design for inheritance or prohibit it". This is a bit of a religious topic in the dev community - I agree with the sentiment, but others prefer everything to be as open to extension as possible.

like image 41
Jon Skeet Avatar answered Sep 28 '22 01:09

Jon Skeet