Here is the code, I defined two class named Father and Son, and create them in the main function:
public class Test {
public static void main(String[] args) {
Father father = new Son();
}
}
class Father {
private String name = "father";
public Father() {
who();
tell(name);
}
public void who() {
System.out.println("this is father");
}
public void tell(String name) {
System.out.println("this is " + name);
}
}
class Son extends Father {
private String name = "son";
public Son() {
who();
tell(name);
}
public void who() {
System.out.println("this is son");
}
public void tell(String name) {
System.out.println("this is " + name);
}
}
and I got the output like this:
this is son
this is father
this is son
this is son
But I can not understand how this happened? Anyone can tell me why?
Let’s start with the constructor of
Son.Father’s constructor is called.
Because
who()is overridden bySon, theSon‘s version will be called, printing “this is son”.tell()is also overridden but the value passed in isFather.name, printing “this is father”.Finally, the
who()andtell(name)calls insideSon‘s constructor will be made printing “this is son” and “this is son” respectively.