Can any body tell why the output of following code is "null"? And what is the best way to construct a complex Object and delegate the details to their subclasses?
package com.test;
public class ClassA {
ClassA() {
initHeader();
initBody();
initFooter();
}
void initHeader() {}
void initBody() {}
void initFooter() {}
public static void main(String[] args) {
ClassB a = new ClassB();
System.out.println(a.obj);
}
}
class ClassB extends ClassA {
public Object obj = null;
ClassB() {
super();
}
void initHeader() {
obj = new Object();
}
}
First, the fields of ClassA
are initialized.
The constructor of ClassA
is then called, calling ClassB.initHeader()
.
After that, fields of ClassB
are initialized overriding what initHeader()
had done.