为什么不能将父类分配给子类类型的变量? [英] Why can't I assign a parent class to a variable of subclass type?
问题描述
为什么子类的引用变量不能指向父类的对象?即
Why reference variable of child class can't point to object of parent? i.e
Child obj = new Parent();
但是我们可以反之亦然 请用内存视图(堆)回答
However we can do vice versa Kindly answer with memory view (heap)
推荐答案
没有理由与内存有关.这要简单得多.子类可以通过添加新方法来扩展其超类的行为.虽然没有给出,但超类具有其子类的所有方法.请看以下示例:
There is no reason which has something to do with the memory. It's much more simple. A subclass can extend the behaviour of its superclass by adding new methods. While it is not given, that a superclass has all the methods of its subclasses. Take the following example:
public class Parent {
public void parentMethod() {}
}
public class Child extends Parent {
public void childMethod() {}
}
现在让我们考虑一下,如果将Parent
的实例分配给类型为Child
的变量,将会发生什么情况.
Now let's think about what would happen if you could assign an instance of Parent
to a variable of type Child
.
Child c = new Parent(); //compiler error
由于c
的类型为Child
,因此可以调用方法childMethod()
.但是,由于它实际上是一个Parent
实例,没有这种方法,因此将导致编译器或运行时问题(取决于检查的完成时间).
Since c
is of type Child
, it is allowed to invoke the method childMethod()
. But since it's really a Parent
instance, which does not have this method, this would cause either compiler or runtime problems (depending on when the check is done).
相反,这没问题,因为您不能通过扩展类来删除方法.
The other way round is no problem, since you can't remove methods by extending a class.
Parent p = new Child(); //allowed
Child
是Parent
的子类,因此继承了parentMethod()
.因此,您可以节省调用该方法.
Child
is a subclass of Parent
and thus inherits the parentMethod()
. So you can invoke this method savely.
这篇关于为什么不能将父类分配给子类类型的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!