Raj Kumar Bindal wrote:Can anybody tell me the reason for this?
Subclassing indicates an "is a" relationship between the superclass and the subclass - but it only goes in one direction. Let's give the classes more concrete names instead of "derived" and "base" to make it more clear:
If you think about it, it's no suprise that you can't write:
Raza Mohd wrote:We cannot cast base class to super class!
Why are you all using non-Java nomenclature? The Java terms are "superclass" and "subclass". Which is supposed to be th bease class and which the superclass? I think that question is at best confusing, but one can always cast a subclass object to its superclass.
Why you should want to cast to a superclass, may be another interesting question.
Correct, a ClassCastException is thrown. But it will most definitely compile, because of the following example:
If you would attempt that with a new Tiger() you would indeed get an exception, because no matter how hard you tell it, a tiger will never behave like an elephant.