One of my classes inherits from a class in a framework I use. The superclass calls a method in its constructor which I overwrite in my own class. The method uses a field I want to initialize before it is called by the super constructor to avoid a NullPointerException.
Is there any way to do this?
Here is a synthetic test scenario, I want c
in Child
to not be null when call
is called.
public class Test {
public static class Parent {
public Parent() {
super();
call();
}
// only called from parent constructor
public void call() {
System.out.println("Parent");
}
}
public static class Child extends Parent {
private Child c = this;
public Child() {
super();
}
// only called from parent constructor
public void call() {
System.out.println("Child, c is " + (c == null ? "null" : "this"));
}
}
public static void main(String[] args) {
new Child();
}
}
Prior to Java 7, that was possible. I could get by with stunts like this:
public static class Child extends Parent {
private Child c;
private Child(Object unused) {
super();
}
public Child() {
this(c = this);
}
// only called from parent constructor
public void call() {
System.out.println("Child, c is " + (c == null ? "null" : "this"));
}
}
Now, that won't work anymore. I appreciate the additional safety, but the call from super destroys any safety gained by it and reduces the flexibility.
I'd like a way to circumvent this restriction. As an alternative, I'd like to know what's gained by an restriction that spares the super constructor case.