Object composition in OOP refers to combining two or more different classes with purpose of creating new, more complex class. In case of composition, an object "owns" another object, rather than just use it, which means if main object will be destroyed, all internal objects should be destroyed as well. In case of aggregation, which is a closely related concept to composition, you can say an internal object is a part of the main object, but is still independent and can exists on its own.
Inheritance is another tool of establishing relationships between classes. Class may inherit the properties and methods of its superclass. Subclasses may override some methods and properties to modify the default behavior of parent class. You can read more about inheritance in OOP here. Consider inheritance as "IS-A" relationship between classes and composition as "HAS-A" relationship.
Advantages of object composition and aggregation over inheritance
- There is principle, which sounds like "favor object composition over class inheritance". Composition over inheritance in OOP is the principle that classes should achieve polymorphism and code reuse by composition, instead of through inheritance. And there are reasons for existence of this principle.
- In most cases "HAS-A" relationship is more semantically correct than "IS-A" relationship between classes.
- Composition is more flexible than inheritance. You can change implementation of class at run-time by changing included object, thus changing behavior of it, but you can't do this with inheritance, you can't change behavior of base class at run-time.
- Inheritance breaks encapsulation. By inheriting from a class you're coupling child class with number of potential implementation details of the parent.
- A design based on object composition usually will have less classes.
- It is possible to implement "multiple inheritance" in languages which do not support it by composing multiple objects into one.
- There is no conflict between methods/properties names, which might occur with inheritance.
Downsides of composition and aggregation are:
- The behavior of the system may be harder to understand just by looking at the source code, since it's more dynamic and more interaction between classes happens in run-time, rather than compile time.
- Composition approach might require more code and time effort.
- A design based on object composition usually will have more objects.
- Object composition refers to combining two or more objects to create new one. "Class A owns class B" relationship established between objects.
- Object aggregation means same as composition, but establishes "Class A contains class B" relationship type.
- Inheritance establishes "IS-A" relationship between classes and composition/aggregation is "HAS-A" relationship.
- Prefer composition over inheritance, since it has a lot of advantages.