Monday, August 16, 2010

Inheritance and the default superclass constructor.

In this short article I will write about the situation, when we extend some class but its default constructor is not accesible for us. For example it has a private modifier or a default one and we are in a different package. If this is a case, we have to remember to use another (accessible) superclass constructor in our subclass constructor. If we don't do it, a compiler will try to insert a call to the default constructor super() which obviously will not work. Below is an example of this:
 class U1 {
private U1() { }
public U1(int x) { }
}
class U2 extends U1 {
U2() {
System.out.println("U2 construction...");
}
}

To mitigate the situation we should explicitly use the public but not default constructor as in the following code:
 class U1 {
private U1() { }
public U1(int x) { }
}
class U2 extends U1 {
U2() {
super(5);
System.out.println("U2 construction...");
}
}

No comments:

Post a Comment