Java中的对象类型混淆

J.z*_*hou 1 java

public class Test {
    public static void main(String[] args){
        B b=new B();
        A a1=new A();
        A a2=b;               
        a1=b;
        a1.printDescription(); //which prints I'm B
        a2.printDescription(); //which also prints I'm B 
    }
}
class A{
    public void printDescription(){
        System.out.println("I'm A");
    }
}

class B extends A{
    public void printDescription(){
        System.out.println("I'm B");
    }
}
Run Code Online (Sandbox Code Playgroud)

在搜索之后,我找到了一个解释混乱的Java多态,它说:"即使x被明确声明为类型A,它也被实例化为B类的对象,所以我将运行doIt()方法的版本,即在B类中定义."但是在我使用类A构造函数实例化对象之后,它仍然打印"我是B",所以任何人都可以为我解释这个吗?

Era*_*ran 5

    B b=new B(); // b refers to an object of class B
    A a1=new A(); // a1 refers to an object of class A
    A a2=b; // a2 refers to an object of class B              
    a1=b; // now a1 refers to an object of class B
Run Code Online (Sandbox Code Playgroud)

a1a2被分配的参考b,这是指类的一个对象B.因此B,printDescription对于两者都执行了类的实现,并且两者都得到了"我是B"输出.