What is Composition in Object Oriented World?
Compositionis a method of reuse in which new functionality is obtained by creating an object composed of other objects. The new functionality is obtained by delegating functionality to one of the objects being composed. Sometimes it is called aggregation or containment, although some authors give special meanings to these terms.
For example:
- Aggregation – when one object owns or is responsible for another object and both objects have identical lifetimes (GoF)
- Aggregation – when one object has a collection of objects that can exist on their own (UML)
- Containment – a special kind of composition in which the contained object is hidden from other objects and access to the contained object is only via the container object (Coad)
Composition can be by reference or by value. C++ allows composition by value or by reference. But in Java all we have are object references!
Advantages and Disadvantages Of Composition
Some pros and cons of object oriented composition are listed here.
Advantages of Composition
- “Black-box” reuse, since internal details of contained objects are not visible
- Contained objects are accessed by the containing class solely through their interfaces
- Each class is focused on just one task
- Fewer implementation dependencies
- Good encapsulation
- The composition can be defined dynamically at run-time through objects acquiring references to other objects of the same type
Disadvantages of Composition
- Interfaces must be carefully defined in order to use many different objects as composition blocks
- Resulting systems tend to have more objects

Add A Comment
You must be logged in to post a comment.