Java inheritance problem

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:

clipboard.png

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!

Mar.10,2021

Private fields are not overwritten.


the concept of inheritance is not fully understood.
Son inherits the getName () method here, while private properties and methods decorated with private are not inherited, and in the Son class you do not override the getName () method, so when you instantiate the Son class: Son test=new Son (); , will advance the constructor of the parent class, initialize the properties in the parent class, then the getName () method called is the method in the parent class, and the name attribute in the parent class is initialized to "Father", so the output is "Father". private String name= "son" in the Son class; is a piece of junk code that is of no practical use and will not be called. You can mouse over the property and it will prompt you that the property is not used.


for the code: there is no getName method in the subclass, of course, the method of the parent class is called in the parent class, and the output is father.
for polymorphism: polymorphism is implemented by the object of the subclass pointing to the reference of the parent class. In your code, the object is new Son (), is a subclass, and the reference test is also a subclass, so there is no polymorphism.

Menu