This week's book giveaways are in the Cloud and AI/ML forums. We're giving away four copies each of Cloud Native Patterns and Natural Language Processing and have the authors on-line! See this thread and this one for details.
Please always say where such questions come from; author, book title, edition number or year, and page number are usually sufficient information.
Your Rodent object is not a Capybara object. It is not created from the Capybara class, but the compiler knows that some rodents are indeed capybaras, so it must permit the compilation with that cast. You are assuring the compiler that you know it will be a capybara. At runtime, however, the rodent isn't a capybara, so the JVM complains with an exception.
This behaviour with casting is different from the behaviour you would get with generics: Foo<Capybara>. If you use generics, the javac tool tests every type to see whether it is certain it is correct. If you use a cast, however, you are assuring the javac tool that you know you are right . . .
Except that the comment isn't correct. That code does not throw ClassCastException.
yes you are right because superclass reference pointing to subclass object so at runtime it points to subclass object there for it can be casted, may be I am wrong but I thought in that way it works, please any way that it cast can happen explain sombody
posted 2 months ago
A few suggestions about casting:-
1: If you find you are casting references frequently, you probably have something wrong with the hierarchy of classes extending one another.
2: If you cast primitives, you can convert them from one type to another: (int)123.456 is an expression of type int, not double.
3: If you cast reference types, you can only cast them to the type they already have: you can say (Object)rodent, (Animal)rodent, (Rodent)rodent, or (Capybara)rodent, but only if rodent already is type Capybara at runtime.
4: You usually have to use casts on reference types and instanceof when writing an equals() method; this is an exception to my No 1.
5: Questions about casting are good for cert. exams, but casting of reference types is usually a bad idea in real‑life code.