How to understand upward transition

Code
. Parent class.
public class Person {

public Person(){
    
}
public void dri(){
    System.out.println("dri");
}

}
. Subclass.
public class Son extends Person {

public Son(){
   super();
}
public void dri(){
    System.out.println("dri");
}

public static void main(String[] args){
    Person p=new Son();
    p.dri();//:dri
}

}
question:
Person p=new Son (); the p reference here points to the real class new Son (); in the subclass. This should be the upward transformation. The upward transformation will lose the methods unique to the subclass. Why is it that instead of calling the dri () method in the parent class, the dir () method in the subclass is called instead? That"s weird

Nov.11,2021

you this is the reference of the parent class to the object of the subclass, which is the embodiment of java polymorphism. According to the principle of "compile to the left, run to the right", the compiler thinks that the Person object has a dri () method and does not report an error, while the runtime executes the dri method of Son because p is actually a Son object. In fact, in the upward transformation, what is lost is the method unique to the subclass, while the method with the same name will not be lost, which is also the meaning of interface.

Menu