I am trying to understand the phrase "favor composite over inheritance".
Could someone give me a real life example why composition is better than inheritance.
Also if there are any drawbacks?
I am trying to understand the phrase "favor composite over inheritance".
Could someone give me a real life example why composition is better than inheritance.
Also if there are any drawbacks?
Inheritance is when a class is a type of another and shares the base functionality and properties of other classes of the same type.
e.g Vehicle -> Car
.
Vehicle might have properties (composition) like weight
or topSpeed
that all classes inherited from it will share.
Composition is the specific makeup of the properties of a class, e.g. Car -> int numDoors
. Methods also represent composition, but often with overridden child class implementations in the case of inheritance. For example, the drive
method of Vehicle
might have common implementation related to gas consumption, while Car
could override that method by perhaps first calling the base method of Vehicle
(super.drive()
), and then further specifying its own specific process.
Also see http://en.wikipedia.org/wiki/Composition_over_inheritance.