Why can't reference to child Class object refer to the parent Class object?

后端 未结 14 1159
执念已碎
执念已碎 2020-12-17 10:50

I was explaining OOP to my friend. I was unable to answer this question. (How shameful of me? :( )

I just escaped by saying, since OOP depicts the real world. In rea

14条回答
  •  生来不讨喜
    2020-12-17 11:37

    If you take a parent class and extend it the class has all the features the parent class has plus some more.

    If you assign an object of the type child to an object of the type parent like:

    Parent aParent = aChild;
    

    you reduce the interface of the child object to the features of the base class. This is perfectly ok because it means that some new features of the child aren't used in that context.

    If you do it the other way round and try to cast a base class to a child you would end up with an object that could live up the expectations on its interface.

    For example you define a base class like:

    Child extends Parent
    
     void doSomeSpecialChildStuff...
    

    Now you create a Parent and assign it to a child object.

    Parent aParent = new Child()
    

    Your programming language now thinks the aParent object is a Child. The problem is that now it would be perfectly valid to this:

     aParent.doSomeSpecialChildStuff()
    

    Now you are calling a method that isn't defined for the object but the interface of the object says it is defined.

提交回复
热议问题