[英]Super class reference to sub class in java
我試圖使用父類引用子類對象。 根據完全參考Java,父類可以引用子類,但是它只能訪問父類中已經聲明的那些字段(完全參考Java第8版,頁面編號:166,倒數第二段)。
據完整參考
重要的是要理解,引用變量的類型(而不是它引用的對象的類型)決定了可以訪問哪些成員。 也就是說,將對子類對象的引用分配給超類引用變量時,您將只能訪問由超類定義的對象的那些部分。 這就是為什么plainbox即使引用BoxWeight對象也無法訪問權重的原因。 如果您考慮一下,這是有道理的,因為超類不知道子類添加了什么。 這就是為什么前面片段中的最后一行代碼被注釋掉的原因。 Box引用無法訪問權重字段,因為Box沒有定義一個。
現在,我正在使用此示例。 父類Box.java
public class Box{
int length;
int breadth;
int height;
Box(int length, int breadth, int height){
this.length = length;
this.breadth = breadth;
this.height = height;
}
public void getAll(){
System.out.println("Length"+this.length+"\nBreadth"+this.breadth+"\nHeight"+this.height);
}
}
子類BoxWeight.java
public class BoxWeight extends Box{
int weight;
BoxWeight(int length, int breadth, int height, int weight){
super(length,breadth,height);
this.weight = weight;
}
public void getAll(){
System.out.println("Length"+this.length+"\nBreadth"+this.breadth+"\nHeight"+this.height+"\nWeight"+this.weight);
}
public int getWeight(){
return this.weight;
}
}
實現類
public class Implementation{
public static void main(String args[]){
Box simpleBox = new Box(10,10,23);
BoxWeight boxWeight = new BoxWeight(10,10,10,30);
System.out.println("box result");
simpleBox.getAll();
System.out.println("box weight result");
boxWeight.getAll();
simpleBox = new BoxWeight(10,10,10,560);
System.out.println("Child class reference result");
simpleBox.getAll();
//System.out.println(simpleBox.getWeight());
}
}
輸出是
box result
Length10
Breadth10
Height23
box weight result
Length10
Breadth10
Height10
Weight30
Child class reference result
Length10
Breadth10
Height10
Weight560
我的問題是,當我用父對象引用子類時,為什么可以通過父類對象訪問子類的成員變量。 根據完整的參考java,這不應發生。
由於getAll()
是公共實例方法,因此它是“虛擬的”: BoxWeight
的實現BoxWeight
覆蓋 Box
的實現。
您誤解了正在閱讀的文章。 Box
類不會以任何方式“引用” BoxWeight
或BoxWeight.weight
或BoxWeight.getAll()
; 相反,您只是簡單地調用simpleBox.getAll()
,並且由於simpleBox
是simpleBox
的實例, BoxWeight
getAll()
的相關實現是BoxWeight
。
在上面的示例中,通過父類對象訪問子類的成員變量的位置?
將BoxWeight
對象分配給simpleBox
(Box類參考變量)后, simpleBox
僅訪問方法getAll()
。 調用的getAll()
方法屬於BoxWeight
類。 發生這種情況的原因是,超類Box
和子BoxWeight
中都存在具有相同簽名的getAll()
方法,這是方法覆蓋的標准。 因此,子類(BoxWeight)對象simpleBox
覆蓋了getAll()
方法。
感謝大家的支持。 實際上我得到了答案,這是由於動態方法分派而發生的。 謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.