Thursday, February 11, 2010

Anonymous class implementing interface

Why is this not allowed:
JPanel panel = new JPanel(...) implements Scrollable {
    ...
};

I've ended up trying to write something like that several times - and each time I start to wonder what is wrong! A problem is of course that you could not directly access the methods of the implemented interface, but you could still have instanceof'ed and cast'ed it. Some interfaces are also just used for marking, e.g. Cloneable.

It is allowed with a local class:
class ScrollableJPanel extends JPanel implements Scrollable {
    ScrollableJPanel() {
        super(...);
    }
    ...
}
JPanel panel = new ScrollableJPanel();
The restriction seems arbitrary.

PS: Oh my god Blogger sucks. I have GOT to get away from this crappy blogging software. How is it possible to not have made any progress the last 5 years?!

1 comment:

  1. Thanks Endre, I agree that restriction in Java does seem arbitrary with interfaces. Also came across good reference here:

    Java Anonymous class and interface

    ReplyDelete