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

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!

If it was valid, what would you expect when you read aChild.prop3? It is not defined on aParent.


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.

Tags:

C#

.Net

C++

Java