Need clarification about inheritance and exceptions-Collection of common programming errors
Other answers have explained the over-ridden method; however, there’s another issue. You said that:
They are all instance of Car so what’s happening here?
But to the compiler, they are not all instances of Car – the compiler will look at the type of the variables:
Vehicle v = new Car();
Car c = new Car();
Vehicle c2 = (Vehicle) v;
At compile time, v
is treated as a Vehicle
, c
as a Car
, and the exceptions will be handled accordingly. At runtime, the JVM knows that v
actually contains a Car
, but that’s different.