Inscrivez-vous ou connectez-vous pour rejoindre votre communauté professionnelle.
This actually a debatable question of Object Oriented Programming design, if one generalise it.
The answer is very subjective as per the requirement. It is not necessary that Composition over inheritance will always have befits.
It is as simple as it means.
Composition = "has a" relationship
Inheritance = "is a" relationship.
In simple words, if the requirement demands "is a" relationship, inheritance should be used.
If the requirement demands "has a" relationship, composition should be used.
Let me explain this with an example:
We want to store key values in our program.
In order to achieve this,
In Inheritance:
Extend HashMap and call super.put(key, value) and myvalue=super.get(key).
In Composition:
Create an object of HashMap
HashMap myMap = new HashMap<kyeOjbectType,valueObjectType>();
myMap.put(key,value) and myMap.get(key);
In above example Composition is better approach.
Lets take another example of Car that extends MotorVehicle class.
MotorVehicle has members like Engine, Fueltank, Accelerator, Break etc.
Car is a MotorVehicle.
Where as, none of Engine, Fueltank, Accelerator, or Break is a MotorVehicle.
MotorVehicle has an Engine. MotorVehicle has a Fueltank. etc.
Here, instead of Car having a MotorVehicle and access Engine, Fueltank etc., it is better to inherit the members.
Hope this answers the quesetion.