Sometimes casting up the inheritance tree gives runtime error.Can anybody explain actually when it will give runtime erro during casting and when will it not? subclass=(subclass)superclass- will it give runtime error? [ May 25, 2004: Message edited by: Barry Gaunt ]
A runtime error is caused (ClassCastException specifically) when you try to cast something to a type that it is not.
For example, look at this code:
In this example, our reference variable, a, references an object of type Cat. Therefore, line 1 will execute fine as we're casting something of type Cat to type Cat - that is perfectly legal.
However, line 2 will cause an error because a Cat is not a Dog. The cast is illegal and will cause a ClassCastException at run time.
It's not that complicated, really - you get a ClassCastException when you try to cast an object to a class that it can't be cast to.
Thanks a lot for the detailed explaination.How about the following? Animal a = new Animal(); Cat c=new Cat(); c=(Cat)a; Will the above passes the runtime?Can an animal be casted in to a cat?Please let me know.Thanks
Animal a = new Animal(); Cat c=new Cat(); c=(Cat)a;
No the above will give u a ClassCastException. You r trying to cast a superclass object to a subclass object which cannot be done. Although opposite of this will work. The following code will work
You must have tried and know the answer for your query. The explanation is :-
ClassCastException occurs whenever the actual object does not have a "is a" relationship with the class it is being casted to.
Lets analyze this rule in context with the ablve example:- Cat "is a" animal. So if a cat object is casted to an animal its well and good.
Example cited in the second post first casts the cat object to an animal. So when this object is being casted to a Dog, obviously exception occurs as Cat "Is NOT a" Dog.
Creating an Animal object and casting to a Cat is again not aceptable as Animal "is NOT a" cat .. only reverse is true.