Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is composition as it relates to object oriented design?

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?

like image 932
DaveDev Avatar asked Aug 09 '10 14:08

DaveDev


People also ask

What is meant by the composition of an object?

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.

What is composition in OOP with example?

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.

Which two of the following are types of object composition?

There are two types of composition: association and aggregation.

What is composition in C++ with examples?

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.


1 Answers

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

like image 111
FrustratedWithFormsDesigner Avatar answered Sep 20 '22 19:09

FrustratedWithFormsDesigner