The following code snippet will result in a run-time:
class Vehicle {
public void printSound() {
System.out.print(\"vehicle\");
}
}
class Ca
In theory, it would be possible for a compiler to say to itself: "v
is local variable, that is assigned to be a Car
. At no point prior to the attempted cast to Bike
does it change its value, and there is no way for Car
to be successfully cast to Bike
. Therefore, this is an error."
However, I know of no Java compiler that will do that analysis for you. It's really only worthwhile in the simplest of cases. Instead, the behavior is that the compiler sees the cast, and reasons that it is possible to cast a Vehicle
to a Bike
, and so it allows it.
In general, that's what a cast means: it tells the compiler that even though this assignment might fail, you're pretty certain that it won't. In exchange for allowing the code to compile, you assume the risk of a run-time exception.