Saturday, February 27, 2016

OOPS : Why-cant-reference-to-child-class-object-refer-to-the-parent-class-object

 aChild is a superset of aParent's abilities. 
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" ? 
class Animal {}
class Fox : Animal {}
class Fish : Animal {}

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

No comments:

Post a Comment