Let's say I want a class MyClass that, among other things, has a property representing a vehicle.
The vehicle can be a car or motorcycle.
In case of a car, I want to be able to retrieve its steering wheel.
EDIT: My fundamental assertion is that a motorcycle does not have a steering wheel, so I would like to avoid having something like a getSteeringWheel in a Motorcycle class.
I see two solutions :
- An abstract Vehicle class extended by two classes : Car and Motorcycle
The problem is that from a MyClass object, to retrieve the type of steering wheel I have to do something like this:
Vehicle vehicle = getVehicle();
if (vehicle instanceof Car) {
SteeringWheel steeringWheel = ((Car) vehicle).getSteeringWheel();
}
which I suppose is not very good.
- A concrete Vehicle class containing everything
I would then do something like this:
Vehicle vehicle = getVehicle();
if (VehicleTypeEnum.CAR.equals(vehicle.getType())) {
SteeringWheel steeringWheel = vehicle.getSteeringWheel();
}
But Vehicle would be an akward class, because if the object's type is MOTORCYCLE then the getSteeringWheel() method does not have much sense.
Which of is better? Is there another solution? Thank you!