Java Reference
In-Depth Information
public class D extends A {
}
}
public class E extends A {
public class F extends B {
}
}
The situation becomes trickier when you want to inherit a top-level class from an inner class:
public class G extends A.B {
// This code won't compile
}
Before I discuss why the above code would not compile, recall that you must have an instance of the enclosing
class before you can create an instance of an inner class. In the above case, if you want to create an instance of class
G (using new G() ), you must also create (indirectly though) an instance of A.B , because A.B is its ancestor class. Here,
A.B is an inner class. Therefore, in order to create an instance of the inner class A.B , you must have an instance of its
enclosing class A . Therefore, you must create an instance of class A before you can create an instance of class G . You
must also make the instance of class A available to class G so that it can be used as the enclosing instance when A.B
instance is created while creating an instance of its subclass G . The Java compiler enforces this rule. In this case, you
must declare a constructor for class G , which accepts an instance of class A and calls the ancestor's constructor on that
instance. The above class declaration for class G must be changed to the following:
public class G extends A.B {
public G(A a) {
a.super(); // Must be the first statement
}
}
In order to create an instance of class G , you should follow two steps:
// Create an instance of class A first
A a = new A();
// Pass class A's instance to G's constructor
G g = new G(a);
You can combine the above two statements into one statement:
G g = new G(new A());
Note that inside G 's constructor you have added one statement: a.super() . The compiler requires this to be the
first statement inside the constructor. At the time of compilation, the compiler modifies a.super() to super(a) . Here,
super(a) means call the constructor of its ancestor, which is class B , passing the reference of class A . In other words,
with the above coding rule, the Java compiler ensures that the constructor of class B gets a reference to its enclosing
class A when the instance of class B is created.
Search WWH ::




Custom Search