Error
Exception in thread "" java.lang.ClassCastException: x cannot be cast to y
Error Type
Run Time
Sample Code
class Car extends Vehicle {
public static void main(String[] args){
Vehicle v1 = new Vehicle();
Car c1 = (Car)v1;
c1.toString();
}
}
Cause
Polymorphic down casting is legal if the referenced object is of sub class type. Compiler trust you that you have done this check and hence allow this to pass through in compile time. If the object found to be of parent type and you are trying to downcast the object to the specific sub class type, it gives the runtime error.
Resolution
Always make a check before doing polymorphic downcasting
class Car extends Vehicle {
public static void main(String[] args){
Vehicle v1 = new Vehicle();
if(v1.instanceOf(Car)){
Car c1 = (Car)v1;
c1.toString();
}
}
}