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.
Question
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();
}
}
Solution
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.
OTHER TIPS
It's not correct that this code doesn't call initHeader
from ClassB.
You can verify it by adding debug output to initHeader
methods of both class.
public Object obj = null;
contain two parts:
public Object obj
obj = null
First part known when constructor runs (at this moment obj initialised as null
by default)
Second part executed after constructor, so after initHeader
and override obj.
Try just replace public Object obj = null;
by public Object obj;