How to achieve extended class function?

I have a Vehicle class. From the car I am expanding the Car class (and some others, such as Bus, Bike ..). Now in my application I do not know which car the user will work with. Therefore, I create a Vehicle object, and then assign it the corresponding object (Car, Bus, ...). After that, I want to name the Car function, but I cannot achieve it. Why?

Vehicle vehicle=null; . . . vehicle=new Car(); vehicle.someMethodFromCar(); //can't reach it 
+4
source share
4 answers

We must use:

 ((Car) vehicle).someMethodFromCar(); //we can reach it 

vehicle is still declared as a vehicle type. This does not change if you assign a vehicle subtype. And the vehicle class does not have additional methods from the Car class. Casting is a way to call methods from subtypes.

+7
source

Your link is determined by the declared type, so in your case you have a link to the vehicle vehicle assigned to the Car object, but java only sees the type of link, so you cannot access any of the Automotive methods. To do this, you need to either assign your object to the variable Car, or specify your link to Car.

+3
source

To achieve this method, you must drop the vehicle in the Car .

+1
source

There are two ways:

  • make the car an abstract class. Define a general method as abstract in a vehicle class. Therefore, when you expand the vehicle, subclasses must apply abstract methods. So when you do

    Vehical v = new Car ();

    v.someOverrideMethod (); he will call the car method.

  • the override method that you want to access at run time in your subclass. So, when you like,

    Vehical v = new Car ();

    v.someOverrideMethod ();

At run time, the JVM will look whose object is created, and this method of the object will be called at run time.

+1
source

Source: https://habr.com/ru/post/1403458/


All Articles