How does the JVM initiate fields in super and subclasses?
Can any authority tell why the output of the following code is "null"? What's the best way to build 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();
}
}
source to share
It is wrong that this code does not call initHeader
from ClassB. You can test it by adding debug output to methods initHeader
for both classes.
public Object obj = null;
contain two parts:
- Ad
public Object obj
- Performance
obj = null
The first part, known when the constructor is run (currently obj is initialized as null
the default) The second part is done after the constructor , so after initHeader
and override obj.
Try to just replace public Object obj = null;
withpublic Object obj;
source to share