Code
parent class:
public class Father {
private String name="father";
public String getName(){
return this.name;
}
}
subclass:
public class Son extends Father{
private String name="son";
/* public String getName(){
return name;
}*/
public static void main(String[] args) {
Son test=new Son();
System.out.println(test.getName());
}
}
I thought the result output was:
son
but the actual result is
father
Screenshot of break point debugging is as follows:
becomes more confused. What if the this shown here is obviously a subclass Son, but when you call the getName method, you get the name property of the parent class?
in inheritance polymorphism:
1. For the coverage of a method, new will tune whoever it belongs to. This is called polymorphism.
2. For the override of member variables, this points to the member variables of the same class, and there is no polymorphism.
is my understanding correct, and if so, why is Java designed this way instead of having similar polymorphism as the method?
ask everyone for advice, thank you!