[英]Object type confusion in 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");
}
}
經過搜索,我找到了Java polymorphism 中的 Confusion的解釋,它說:“盡管 x 明確聲明為類型 A,但它被實例化為類 B 的對象,因此我將運行 doIt() 方法的版本,即在 B 類中定義。”但是在我使用 A 類構造函數實例化對象 a 之后,它仍然打印“我是 B”,所以有人可以為我解釋一下嗎?
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
類的對象。 因此, printDescription
兩個類都執行了B
類的printDescription
的實現,並且得到了這兩個類的“ I'm B”輸出。
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
這是因為綁定晚了 。 您在這里有方法重寫(派生的類實現了一個與基名稱相同的方法)。 這導致將調用保存在變量引用而不是引用類型上的派生最多的類型方法,並將在運行時確定該方法。
例如:
//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();
在代碼a1中,a2和b是指向B實例的引用變量。首先創建一個對象A,如下所示:
A a1 = new A();
但后來您將其指定為“ b”
a1 = b
這就是為什么它從B類而不是從A類執行方法的原因
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.