class Vehicle {}
class Car extends Vehicle {}
public class Sfield {
public static void main(String[] args) {
Vehicle v = new Vehicle();
Car c = (Car)v;
}
}
This example compiles without any problem. But what will happen is... a java.lang.ClassCastException thrown! However there is one situation, when the compiler can help us. If we try to downcast the class from the different inheritance tree the compiler will let us know about it during the compilation time and not the runtime! For instance:
class Vehicle {}
class Car extends Vehicle {}
public class Sfield {
public static void main(String[] args) {
String v = new String("Vehicle");
Car c = (Car)v;
}
}
So if the compiler knows that the downcast will not work for sure it will manifest it with:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:But in the first example it might happen that the v references to the Car object. But it was not possible to verify this at the compilation time.
Cannot cast from String to Car
No comments:
Post a Comment