Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Favor composition over inheritance [duplicate]

Favor composition over inheritance

is very popular phrase. I read several articles and at the end each article says

use inheritance when there is pure IS-A relationship between classes.

An example from this article:

Here between Apple and Fruit there is clear IS-A relationship i.e Apple IS-A Fruit, yet the author has also shown it as Apple HAS-A Fruit (composition) to show the pitfall when implemented with inheritance.

I became somewhat confused here that what is the meaning of statement

use inheritance when there is pure IS-A relationship between classes.

Does using composition over inheritance mean that always try to apply composition even if there is a pure IS-A relationship and leave inheritance only for those cases where composition does not make sense?

like image 998
a Learner Avatar asked Jul 05 '12 11:07

a Learner


People also ask

Why is composition better than inheritance?

Composition offers better test-ability of a class than Inheritance. If one class consists of another class, you can easily construct a Mock Object representing a composed class for the sake of testing. This privilege is not given by inheritance.

What are the disadvantages of using composition over inheritance?

The disadvantage of object composition is that the behavior of the system may be harder to understand just by looking at the source code. A system using object composition may be very dynamic in nature so it may require running the system to get a deeper understanding of how the different objects cooperate.

Why composition is better than inheritance in C#?

The composition approach provides stronger encapsulation than inheritance, because a change to a back-end class does not necessarily break any code that relies on the front-end class. The main advantages of composition is, with carefully designed interfaces we can change references of back end classes at runtime.

Is composition and inheritance same?

Inheritance and composition are two programming techniques developers use to establish relationships between classes and objects. Whereas inheritance derives one class from another, composition defines a class as the sum of its parts.


1 Answers

When you use inheritance to reuse code from the superclass, rather than to override methods and define another polymorphic behavior, it's often an indication that you should use composition instead of inheritance.

The java.util.Properties class is a good example of a bad use of inheritance. Rather than using a Hashtable to store its properties, it extends Hashtable, in order to reuse its methods and to avoid reimplementing some of them using delegation.

like image 191
JB Nizet Avatar answered Oct 04 '22 15:10

JB Nizet