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

后端 未结 14 1152
执念已碎
执念已碎 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:19

    class "Child" extends "Parent"

    "child class object is inherently a parent class object"

     Child aChild = new Child();
     Parent aParent = new Parent();
     aParent = aChild;// is perfectly valid.
     aChild = aParent;// is not valid.
    

    in a code segment like a normal assignment operation, the above is read from right to left. line 3 of the code segment reads - "aChild (a Child class object) is a Parent" (due to inheritence child class objects become superclass objects inherently) thus line no.3 is valid.

    whereas in line no.4 it reads, "aParent (a Parent class object) is a child" (inheritence doesn't say that superclass objects will become child class objects. it says the opposite) thus line no.4 is invalid.

提交回复
热议问题