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");
}
}
搜索之后,我找到了一个解释Confusion in Java polymorphism,其中说:"即使x被明确声明为A类,它也被实例化为B类的对象,所以我将运行该版本的在类B中定义的doIt()方法。"但是在我使用类A构造函数实例化对象之后,它仍然打印了"我是B"所以任何人都可以解释这个对我来说?
答案 0 :(得分: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
a1
和a2
都分配了引用b
,引用了类B
的对象。因此,B
的{{1}}类的执行被执行,两者都得到了“我是B”输出。
答案 1 :(得分:1)
a1=b;
b
是B
,您可以将其分配给a1
。 无关紧要在编译时类型所说的内容。重要的是它运行时的实际情况。由于您为a1
分配了B
,因此它是B
。
逐行:
B b=new B(); //b is a B
A a1=new A(); //a1 is an A, b is a B
A a2=b; //a1 is an A, b is a B, and a2 is the same B as b
a1=b; //a1, a2 and b are all references to the same B value
答案 2 :(得分:0)
这是因为late binding。这里有方法覆盖(派生类实现了一个与base同名的方法)。这导致将调用保存在变量引用而不是引用类型上的派生程度最大的类型方法,这将在运行时确定。
例如:
//This is an A-type reference, referencing to a A-type object
A a = new A();
B b = new B();
//The A-type reference, is now referencing to the B-type object.
//The old, A-type object held will be set for garbage collection.
A a = b;
//This will call the mostly derived type referenced method (which is B),
//which prints "I'm B"
a.printDescription();
答案 3 :(得分:0)
在你的代码中,a1,a2和b是你的referance变量,它指向B的实例。 首先创建A的对象
A a1 = new A();
但稍后您将其标记为“b”为
a1 = b
这就是为什么它从B类执行方法而不是从A类执行
答案 4 :(得分:0)