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

前端 未结 1 598
醉梦人生
醉梦人生 2020-12-22 06:43

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 a

相关标签:
1条回答
  • 2020-12-22 07:28

    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.

    0 讨论(0)
提交回复
热议问题