A parent class reference can point to derived class object but vice versa is not possible.Why?
If we see acccording to memory allocated the derived class(if has more attributes) occupy more memory than parent class.So in turn the derived class covers the parent class and so shld be able to point to its object.As according to this parent class shld not be able to pt to derived's object. If not seen according to memory also a derived class as can be said contains parent class shld be able to point to its object...can any one explain why vice versa is not possible
Say, for example, I create classes B and C which derive from A. Because B and C both extend A, it is legitimate to call a B object an A, and a C object an A. But suppose we have an A object. It is not legal to call it a B object, because the object might be a C object.
[ March 07, 2006: Message edited by: Keith Lynn ] [ March 07, 2006: Message edited by: Keith Lynn ]
well it is easeir to think of it this way. if object A has methods getA and getB, then object B extends object A, this means that object B must have the method getA and getB, and additional methods and since we can be sure that any method called on object A is found in object B then we can instantiate a reference of A pointing to B type and as such you will call getA or getB but they are in B and so no problem but if u try to use an instance of B then calling method say getC that might be defined in B that method will not be found in A and such the engine will blow up
Supposed you have a parent class Animal. And derived classes Cat and Dog.
Treating a Cat like an Animal is fine, but can you treat an Animal like a Cat?
You can't necessary refer to an Animal object like a Cat, because it may not be. To tell the compiler that you are correct, you can cast it. But even then, if you are wrong during runtime, it will throw an exception.
According to my view the answer is encapsulated with in the question itself. It's just a matter of ogranizing the thoughts and coming to a conclusion.
Gunj pointed out that the derived class has more attributes & etc. THAT IS EXACTLY THE ANSWER.
Let me present it in this way. A DERIVED CLASS HAS THE POTENTIAL TO ACHIEVE MORE CAPABILITIES THAN ITS PREDECESSORES.
WHEN A DERIVED CLASS REFERENCE TRYING TO REFER TO A PARENT CLASS OBJECT MR. COMPILER QUESTIONS,
MATE, ARE YOU REALLY SURE YOU WANT TO RESTRICT THIS GUY'S CAPABLITIES? THAT'S Y AN EXPLICIT CAST IS NEEDED. IF YOU REALLY SURE THEN GOOD ON YOU....!!
ON THE OTHER HAND WHEN THE PARENT CLASS REFERENCE TRYING TO REFER TO A DERIVED CLASS OBJECT, THERE SHOULD BE ABSOLUTELY NO PROBLEM AS THAT LITTLE REFERENCE VARIABLE CHAP IS TRYING TO IMPROVE HIMSELF BY GAINING MORE CAPABILITIES.
Who says that Object fellow is the most-skilled guy in the world...? Comments please.