[英]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.