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

◇◆丶佛笑我妖孽 提交于 2019-11-29 18:52:31

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.

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