Reputation: 14628
I encounter some code like the following:
BaseClass:
public class BaseClass {
String name = "Base";
public BaseClass() {
printName();
}
public void printName() {
System.out.println(name + "——Base");
}
}
DrivedClass:
public class SubClass extends BaseClass {
String name = "Sub";
public SubClass() {
printName();
}
public void printName() {
System.out.println(name + "——Sub");
}
public static void main(String[] args) {
new SubClass();
}
}
When run the code, the output is:
null——Sub
Sub——Sub
while it should be:
Base——Base
Sub——Sub
I wonder why the BaseClass constructor calls the SubClass method, can anybody explain this? Thanks in advance.
Upvotes: 0
Views: 60
Reputation: 45080
The first line("null——Sub") is printed as a result of printName()
of SubClass
being called from the BaseClass
constructor. When printName()
is called from BaseClass
constructor, since there is an overridden method available in the SubClass
, that printName()
is called.
At this point of time, since the SubClass
constructor is not yet called, the name
field of SubClass
is undefined and thus prints null
.
The second line("Sub——Sub") is printed as a result of printName()
of SubClass
being called from the SubClass
constructor. This time around, the instance fields are loaded and thus, the name
prints the proper value (i.e) "Sub".
The thing to note here is that, both the times, the printName()
method of SubClass
is only called. Just that the first time around(because it's called from the super
class constructor), its instance fields are not defined and the second time around, they are.
Upvotes: 4