posted 16 years ago
Consider the following code:
This code might looks good at first but if you try to compile it, it will fail:
InheritFromNonStaticMemberClass.java:14: an enclosing instance that contains Outer.Inner is required
class SubInner extends Outer.Inner {
^
1 error
This error is because the no-arg constructor of the class Inner (which is the super class at our case) needs an instance of its enclosing class to bind to. Since we know that inner classes cannot leave without their enclosing class instance so you can not call the constructor of the inner class without passing a reference to its enclosed class. So we fix the above code by a special yet might be wierd syntax like this:
in fact this syntax:
outer.super();
in the sub class constructor means that as well as we explicitly call the super class constructor, we send a reference to the enclosed (outer) object so that the inner class can bind to it.
However there is one exception to this:
In this case the compiler is happy since the class SubOuter is instantiated and passes itself to the SubInner constructor and will pass up all the way to the Inner constructor so the Inner class object (the super class) can bind to that implicit SubOuter object reference. In fact the SubOuter object acts on behalf of the Outer object (the super class enclosing class)
Ok, but it's not finished yet! In the first case, if the Inner class does not have a no-arg constructor and instead has a non-default constructor, things get tricky a little bit:
Got the point? We have to create a non-default constructor for the sub class which has arguments including all of the declared super inner class constructor as well as a reference to the enclosing class!