Kaur Manpreet wrote:I had a tough time understanding the ClassCastException thrown at runtime and inconvertible types compile time error.
Well, it is not much difficult to identify if you understand inheritance hierarchy.
Inconvertible compile time error occurs when compiler knows for sure that type of the references are not convertible at all. ClassCastException occurs when casting of references is possible, but at runtime, actual objects are not convertible.
e.g.
This happens because, at line 7, compiler knows that d is a reference of type Dog, and there's no way that it can refer to a Cat object, so, at compile time itself, there is an inconvertible type error.
But at line 9, animal is a reference of type Animal, and there is a chance that it can refer to either Animal, Cat or Dog object. So, compiler doesn't complain about this casting. But at runtime, animal is actually referring to a Cat object, which cannot be converted to Dog object(or, to be specific, a reference of type Dog cannot refer to Cat object), and hence, there is a ClassCastException.
I hope this helps.