As a beginner, I have been learning about composition and inheritance. I realized that when using composition you do not create objects but a composition. I am a bit confused here. Lets say that we are building a human with a head, 2 arms and 2 legs.
Normally, what I would do is create arms legs and head classes and then create the object human which are build up by those. But in composition, you instead build a human class which are linked to other classes? Where am I wrong?
Indeed, you are wrong.
Composition is often considered as an alternative to inheritancy but in both cases you manipulate instances of classes and not only classes as you suppose for the composition case.
With your example, a very bad example of inheritancy would be having :
TwoLegs
class that is two Legs.TwoArmsAndTwoLegs
class (subclass of TwoLegs
) that is two arms but also two legs.HeadAndTwoArmsAndTwoLegs
class (subclass of TwoArmsAndTwoLegs
) that is a head but also two arms and two legs.Human
class (subclass of HeadAndTwoArmsAndTwoLegs
) that is an human but also all the remains.It is not flexible as all classes are strongly related in their hierarchy and the definition itself of their structure.
Here, composition would be to have a Human class that owns 5 fields :
rightLeg
field of the Leg classleftLeg
field of the Leg classleftArm
field of the Arm classrightArm
field of the Arm classhead
field of the Head class