Passing subclass or superclass object to method (e

2020-08-04 09:01发布

问题:

I'm working with some code that needs to send either a superclass or subclass object to a method.

The method public void repair(Vehicle vehicle) will ONLY access methods in the super class object.

public class Vehicle {
    //class stuff
}

public class Car extends Vehicle {
    //class stuff
}

public static void main(String[] args) 
{
    // do stuff to determine whether working with a vehicle or car
    if (someCondition)
    {
        Car = new Car();
        // do some stuff...
        repair(Car);
    }
    else
    {
        Vehicle = new Vehicle();
        // do some stuff...
        repair(Vehicle);
    }
}   

I figure I have three options:

  1. Leave the code as it is, it seems to be working. - I don't like this option, it feels like I'm making assumptions and I suspect car only methods could be accidentally called doing this, leading to unexpected behaviour.
  2. Create a getVehicle() method in car, to return a Vehicle. Then use repair(Car.getVehicle()); - this feels a little better
  3. Change Car = new Car(); to Vehicle = new Car(); which I believe would create an object (vehicle) that can only perform methods of type vehicle. - This feels the safest, as I'm now restricting what can be done, to prevent unexpected behaviour.

Is 3, the best approach, given that the repair method is only ever expecting vehicles?

Also, is there anything I could/should to to the: public void repair(Vehicle vehicle) method declaration?

EDIT: It seems I should be using:

Leave the code as it is

since the repair() method casts the subclass object to a superclass object anyway.

回答1:

There is no definition of repair but I think you want something like this

public abstract class Vehicle {
    //class stuff
}

public class Car extends Vehicle {
   //class stuff
}


public class Garage {
   public void repair(Vehicle vehicle){
   ....
   }
}

Then you can pass any subclass of Vehicle to the repair method. In this case it is only Car but you could extend to have bike, motorcycle etc.

Now you will not need to check with an if statement. You can just pass your object (or Car or anything else) into the repair method.

You main just becomes

public static void main(String[] args)  {
    Garage g = new Garage();
    Vehicle c = new Car();
    Vehicle b = new Bike(); //assuming Bike is a subclass of Vehicle.
    g.repair(c);
    g.repair(b);
}  

If when accessing variable b and c you need Car and Bike specific method then you can change their declarations to be

Car c = new Car();
Bike b = new Bike();