mardi 8 décembre 2015

Best way to avoid explicit casts

I have a class hierarchy like below

Vehicle
|_ TransaportationVehicle has method getLoadCapacity
|_ PassengerVehicle has method getPassengerCapacity

and I have one more class Booking it have a reference to Vehicle.

Now whenever I have to call getPassengerCapacity or getLoadCapacity on vehicle reference I need to type cast vehicle to its concrete implementation like ((PassengerVehicle)vehicle).getPassengerCapacity() and this type of calls spans over multiple parts in the project. So is there any way with which I can avoid these type of casts and my code will look beautiful and clean?

Note: These are not actual classes I have taken these as an example to demonstrate current problem.

Aucun commentaire:

Enregistrer un commentaire