I have an Vehicle class. From Vehicle, I extend Car class (and some others like Bus, Bike..). Now in my application, I don't know what kind of vehicle the user will want to work with. So I create a Vehicle object and later asign it the proper object (Car, Bus, ...). After that I want to call some Car's function - but I can't reach it. Why?
Vehicle vehicle=null;
. . .
vehicle=new Car();
vehicle.someMethodFromCar(); //can't reach it
We have to cast:
((Car) vehicle).someMethodFromCar(); //we can reach it
vehicle
is still declared as a Vehicle
type. That doesn't change if you assign a subtype of Vehicle
. And the Vehicle
class does not have the extra methods from the Car
class. Casting is the way to call methods from subtypes.
Your reference is define by it's declared type, so in your case, you have a Vehicle reference vehicle
assigned to a Car object, but java only sees the type of the reference, so you can't access any of the Car's methods.
In order to do that you need either to assign your object to a Car variable, or cast your reference to Car.
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