I hear (and read on this site) a lot about "favour composition over inheritance".
But what is Compositon? I understand inheritance from the point of Person : Mammal : Animal, but I can't really see the definition of Compostion anywhere.. Can somebody fill me in?
Object composition refers to the logical or conceptual structure of the information, not the implementation or physical data structure used to represent it. For example, a sequence differs from a set because (among other things) the order of the composed items matters for the former but not the latter.
A composition in Java between two objects associated with each other exists when there is a strong relationship between one class and another. Other classes cannot exist without the owner or parent class. For example, A 'Human' class is a composition of Heart and lungs.
There are two types of composition: association and aggregation.
Object Compositions Complex objects are objects that are built from smaller or a collection of objects. For example, a mobile phone is made up of various objects like a camera, battery, screen, sensors, etc. This process of building complex objects from simpler ones is called object composition.
Composition refers to combining simple types to make more complex ones. In your example, composition could be:
Animal: Skin animalSkin Organs animalOrgans Mammal::Animal: Hair/fur mammalFur warm-blooded-based_cirulation_system heartAndStuff Person::Mammal: string firstName string lastName
If you wanted to go totally composition (and get rid of all inheritance) it would look like this:
Animal: Skin animalSkin Organs animalOrgans Mammal: private Animal _animalRef Hair/fur mammalFur warm-blooded-based_cirulation_system heartAndStuff Person: private Mammal _mammalRef string firstName string lastName
The advantage to this approach is that the types Mammal
and Person
do not have to conform to the interface of their previous parent. This could be a good thing because sometimes a change to the superclass can have serious effects on the subclasses. They still can have access to the properties and behaviours of these classes through their private instances of these classes, and if they want to expose these former-superclass behaviours, they can simply wrap them in a public method.
I found a good link with good examples here: http://www.artima.com/designtechniques/compoinh.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With