Ashish Dutt wrote: . . . .
When i run the above code AnimalTest.java I get a class cast exception error. I just need to confirm with you kind folks that is/are my following inferences correct ?
None of the following is correct.
Inference 1: In the try block horse subclass reference variable h is trying to up-cast itself to Animal Super Class so that it could print "Generic Animal eating" when invoked with the eat method as h.eat();
Inference 2: Since Java does not support up casting therefore it throws the ClassCastException error.
Inference 3: So all this boils down to Java allows inheritance to sub classes but gets mad if you try to access its "super" powers.
Sincerely awaiting your reply.
Don’t go on about super powers. Remember you are on the beginners’s forum and somebody will believe you
You are not casting up anywhere. You can
always cast something up to its superclass, but there is hardly ever any benefit to be gained from doing that. What you are doing is telling the compiler, “this is a Horse”, and the compiler is (in this instance) very trusting and will believe you. Or maybe you are promising always to provide a Horse at that point. When you come to execute the cast, the JVM complains it has been lied to (or the promise was broken; the object in question is not a Horse), and if the JVM has a complaint, it always responds with an Exception. In this case a ClassCastException.
What you are doing is casting down towards the subclass. Something
you should avoid as much as possible.because it is very error‑prone. You had designed your inheritance so as to obviate any need for such a cast, and still carried it out regardless.