Wednesday, July 27, 2011

How to inherit an inner class?

Consider the following example,
class A {
class B {
B(int i) {
...
}
}
...
}


Sub-classing B inside class A is very simple because both class B and its sub-class, say C, require the instance of class A and can be done as follows.
class A {
class B {
B(int i) {
...
}
}
class C extends B {
C(int i) {
super(i);
...
}
}
...
}


However, if you want to sub-class B outside class A, as follows,
class C extends A.B {
C(int i) {
super(i);
...
}
...
}


you will get a compiler error as "an enclosing instance that contains A.B is required".

In order to solve this problem, you need to get an instance of A, as follows,
class C extends A.B {
C(A a, int i) {
a.super(i);
}
}


Here is the compelete code.
public class A {
class B {
int i;
B(int i) {
this.i = i;
}
}
}
class C extends A.B {
C(A a, int i) {
a.super(i);
}
public static void main(String[] args) {
A a = new A();
C c = new C(a, 10);
System.out.println("c.i = " + c.i);
}
}