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:
- 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.
- Create a getVehicle() method in car, to return a Vehicle. Then use
repair(Car.getVehicle());
- this feels a little better - Change
Car = new Car();
toVehicle = 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.