Inheritance and composition are similar to what they can achieve, and you allude to this when you say that composition
sounds like multiple inheritance
The fundamental difference can be illustrated in this code example:
Inheritance
class Fruit { ... } class Apple extends Fruit { ... }
Composition
class Fruit { ... } class Apple { this.fruit = new Fruit(); }
The consequences of choosing a design should be obvious here:
Inheritance gives you the added benefit of creating functionality that is accessible to your subclasses, very easily updated, and helps create a logical hierarchical structure for your classes. However, superclasses are often considered volatile, as changing a superclass can have very far-reaching side effects that you will need to feel almost constantly.
Composition , on the other hand, adds an access level between subclasses and their parents. The advantage here is that changes in the “parent” class are far less likely to have far-reaching side effects. The trade-off here is that it increases complexity to some extent.
A good rule of thumb is to think about the semantics of your classes. Think about the relationship between the two classes. If you could say that child is parent , use inheritance; otherwise use the composition. In the above example, we can say that Apple is Fruit , so inheritance probably makes sense here. Again, this is an offer, not a rule!
Check out this article for a deeper explanation.
source share