Can someone explain what's happening here?
Assume Car
and Bike
are subclasses of Vehicle
.
It looks to me like Vehicle v
reference gets cast to a Bike
. I know this is illegal and indeed the compiler spits out ... Car cannot be cast to Bike
.
But shouldn't this be Vehicle
cannot be cast to Bike
? After all, Vehicle v
is a Vehicle
reference.
public class Test {
public static void main(String[] args) {
Vehicle v = new Car();
Bike b = (Bike) v;
// some stuff
}
}
Error message says Car
because this is run time exception. Since by this time it knows the actual instance (Car, Bike, or Vehicle) the Vehicle reference is pointing to, it gives more specific error message.
If this is some exception at compile time, compiler would have mentioned Vehicle
since compiler may not know the actual instance the Vehicle reference is pointing to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With