I generally understand the various flavours of inner class. I have found the below example which is causing me some confusion. The point of confusion is that the main class (AbstractTest) is abstract. This usually means the class cannot be instantiated and that the first concrete subclass must fully implement any previously declared abstract methods. In this case there is also an abstract inner class. When anonymous class one extends AbstractTest this compiles okay even though this anonymous class does not implement the abstract inner class. Where as if there is a regular abstract method (doStuff) in AbstractTest and anonymous class one does implement, then receive error saying abstract method doStuff does not exist. The meaning of abstract seems to not be the same when applied to an inner class as a method. What does an abstract inner class really mean? Does it only mean you must subclass it too through either another inner class or anonymous class? Apologies if this is not clear, I am starting to go round in circles with the inner class variations.
public abstract class AbstractTest { // public method public int getNum() { return 45; }
// public inner class public abstract class Bar { // public inner class method public int getNum() { return 38; } }
// public abstract void doStuff(); // If uncomment this then receive error // because anonymous class does not // implement this method.
// main method public static void main(String args[]) { // anonymous class one AbstractTest t = new AbstractTest() { // anonymous class overriding method public int getNum() { return 22; } };
// anonymous class two AbstractTest.Bar f = t.new Bar() { // anonymous class overriding method public int getNum() { return 57; } }; System.out.println(f.getNum() + " " + t.getNum()); } // end method main } // end class
Petr Blahos
Ranch Hand
Joined: Apr 28, 2004
Posts: 131
posted
0
Hi Craig,
Firstly, the AbstractTest is NOT an abstract class. You can remove the keyword abstract and it will work. You are a sort of mixing 2 problems in the example. Firstly, if you remove the immer abstract class it is all clear I believe.
Now, you cannot instantiate an abstract class. In other words, all methods have to be defined. But you never instantiate the inner class, therefore you don't need to define it. Try to think about it from the compiler point of view. If it has everything it needs, it will just go.
Best regards, Petr
Get a better web browser:<br /><a href="http://www.mozilla.org/products/firefox/switch.html" target="_blank" rel="nofollow">http://www.mozilla.org/products/firefox/switch.html</a>