Thursday, August 19, 2010

Downcasting and a compiler.

Today I will write shortly about the downcasting and especially about the way the compiler can assist us while doing this. Actually it can't do a lot. It trusts us when we do the downcast that it is actually possible. Let's consider this example:
 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:
Cannot cast from String to Car
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.

No comments:

Post a Comment