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

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

    Exactly because aChild is a superset of aParent's abilities. You can write:

    class Fox : Animal
    

    Because each Fox is an Animal. But the other way is not always true (not every Animal is a Fox).

    Also it seems that you have your OOP mixed up. This is not a Parent-Child relationship, because there's no composition/trees involved. This is a Ancestor/Descendant inheritance relation.

    Inheritance is "type of" not "contains". Hence it's Fox is a type of Animal, in your case it doesn't sound right -- "Child is a type of Parent" ? The naming of classes was the source of confusion ;).

    class Animal {}
    class Fox : Animal {}
    class Fish : Animal {}
    
    Animal a = new Fox(); // ok!
    Animal b = new Fish(); // ok!
    Fox f = b; // obviously no!
    

提交回复
热议问题