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
If I have a class, say
class A{
getA(){
}
}
class B extend A{
getB(){
}
}
Now class B
knows two methods getA()
and getB()
.
but class A
knows only getA()
method.
So, if we have class B obj = new class A();
we have made a mess , as it is valid for class B
to reference methods getA()
and getB()
but only getA()
is valid. That explains the issue.
This is my understanding of not allowing child class hold reference of parent class.
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.