Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java casting with superclass reference

Tags:

java

casting

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
    }   
}
like image 237
m0therway Avatar asked Oct 10 '22 10:10

m0therway


1 Answers

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.

like image 70
Sachin Karjatkar Avatar answered Oct 13 '22 11:10

Sachin Karjatkar