Monday, June 12, 2006

Extending Inner Class

Another good thread from javaranch.

class A{}
class B extends A{
public static void main(String args[]){
B b=new B(); // Line 1
}
}

At line 1, basically two objects are created.

First of class A, then of class B. So basically we have two instances here and instance of A act as a subobject which is actually wrapped within intstance of subclass. So, when extending the inner class, an instance of InheritInner must have an instance of Inner class and Inner class always require an instance of Outer class. So, to the constructor of InheritInner which extends Outer.Inner we must also pass the enclosing outer instance of inner class and call the super constructor of enclosing outer instance which will take care of instantiating the inner instance.


class Outer {class Inner {}}

public class InheritInner extends Outer.Inner {
InheritInner(Outer o) {
o.super();
}
public static void main (String[] args){
Outer o = new Outer();
InheritInner ii = new InheritInner(o);
}
}

If the inner class was static(nested class), then calling o.super() is not required, since the inner class will be instantiated without an enclosing outer class instance.

No comments: