Why can't I assign a parent class to a variable of subclass type?

自古美人都是妖i 提交于 2019-11-28 13:01:49

问题


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)


回答1:


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() {}
}

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

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 is a subclass of Parent and thus inherits the parentMethod(). So you can invoke this method savely.



来源:https://stackoverflow.com/questions/43296084/why-cant-i-assign-a-parent-class-to-a-variable-of-subclass-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!