Claudiu Stroe wrote:A reference to an object Animal is equal to a cast from Cat to an Animal and you don't need an explicit cast
Spot-on! An object of a subclass (e.g. a
Cat object) can be assigned to a reference variable of a superclass (e.g. an
Animal or
Object reference variable) without specifying an explicit cast.
Claudiu Stroe wrote:A reference to an object Cat is equal to a cast from Animal to a Cat and you need a cast. It will compile but it will throw a ClassCastException at runtime if Animal is not instanceof Cat
Although the gist of your thoughts is understandable and correct, you probably need to be a little bit more careful about wording and phrasing.
Let's consider your code snippet
Because a
Cat IS-A
Animal, you can assign a
Cat instance to an
Animal reference variable (without the need of an explicit cast). If you want to assign this
Animal reference variable to a
Cat reference variable, you need an explicit cast. Because
Cat IS-A
Animal, the compiler allows you to cast the
Animal reference variable to
Cat. But if the object denoted by the
Animal reference variable IS-NOT-A
Cat, a ClassCastException will be thrown at runtime. To avoid this exception from being thrown at runtime, you can add a check using the
instanceof operator. It returns
true if the object is of the specified type;
false otherwise.
Hope it helps!
Kind regards,
Roel