Say I have two classes
class Driver{
//attributes of driver ,ex: driving licence number
// methods related to driving ,ex: drive(Car) , stop(Car)
changeTyre(Car,Tyre); // sometimes the driver can change the tyres right?
}
class Mechanic{
// Hard mechanical stuff , ex: repairEngine(Car)
changeTyre(Car,Tyre); // Simple.hence sometimes the driver also does
}
Now the implementations of the two changeTyre() methods will be the same.
Now I have two issues,
- There is a repetition (duplication) of code
- It doesn’t seem meaningful to have a Super class containing the
changeTyre(Car,Tyre)method
How these kind of situations handled?
To expand on using composition over inheritance (Willie’s answer), I think you were on the right track in your comment about using ChangeTyre like
car.ChangeTyre(Tyre).Each mechanic or driver will be associated to a car, so they can have a Car property –
They
changeTyremethod of Driver and Mechanic might be the same, but the actual logic to change the tyre will live in one place. I don’t think inheritance works because a mechanic is not a driver, and inheritance supports an “is-a” relationship. It may not make sense to forcechangeTyreto a superclass (say Person), because not every class that inherits from Person would need to have achangeTyremethod. See this question for more information about composition over inheritance.