Several times I thought it will be good to have overridable constructor in Java.
"Overridable" means the logic of construction can be overriden and/or extended in descending classes in the same way it is possible to override normal methods, i.e. with ability to call parent method AFTER the child.
This task can be formulated as to have a method, say, called init()
which is called at construction time, but only in the last constructor of the stack.
Like:
public class InitializationOverride {
public static class A {
A() {
System.out.println("Constructor of A");
}
void init() {
System.out.println("Init of A");
}
}
public static class B extends A {
B() {
System.out.println("Constructor of B");
}
@Override
void init() {
System.out.println("Init of B");
}
}
public static class C extends B {
C() {
System.out.println("Constructor of C");
}
@Override
void init() {
System.out.println("Init of C");
}
}
public static void main(String[] args) {
new A(); // should print "Constructor of A, Init of A"
new B(); // should print "Constructor of A, Constructor of B, Init of B"
new C(); // should print "Constructor of A, Constructor of B, Constructor of C, Init of C"
}
}
The obvious way is to write
public static void main(String[] args) {
new A().init();
new B().init();
new C().init();
}
but this doesn't guarantee init()
is not forgotten to call.
Is it possible to do somehow?
UPDATE
It is not known at design time, which class will be "last". It is expected, that class tree will be developed in future.
UPDATE 2
Here is the solution with reflection and constructor code requirement to call currentStage()
at the end:
public class InitializationOverride {
public static class A {
A() {
System.out.println("Constructor of A");
currentStage(A.class);
}
void currentStage(Class<?> cls) {
if( cls == getClass() ) {
init();
}
}
void init() {
System.out.println("Init of A");
}
}
public static class B extends A {
B() {
System.out.println("Constructor of B");
currentStage(B.class);
}
@Override
void init() {
System.out.println("Init of B");
}
}
public static class C extends B {
C() {
System.out.println("Constructor of C");
currentStage(C.class);
}
@Override
void init() {
System.out.println("Init of C");
}
}
public static void main(String[] args) {
new A(); // should print "Constructor of A, Init of A"
new B(); // should print "Constructor of A, Constructor of B, Init of B"
new C(); // should print "Constructor of A, Constructor of B, Constructor of C, Init of C"
}
Is it possible to write simpler?