Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reach extended class' function?

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
like image 972
c0dehunter Avatar asked Dec 16 '22 02:12

c0dehunter


2 Answers

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.

like image 146
Andreas Dolk Avatar answered Dec 18 '22 16:12

Andreas Dolk


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.

like image 30
Francisco Paulo Avatar answered Dec 18 '22 16:12

Francisco Paulo