Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to Favor Inheritance Over Composition

This question seems to be repetition, but it's not. I googled, bus could not get conceptual clarity. There are many Animal, Cars kinds of example. But, I want to understand the basic logic. Generally it is said, Favor Composition Over Inheritance, as it offers many advantages. In that case, why inheritance is provided as the one of the main concepts of OOPs at all. My question is when to favor the inheritance over composition?

like image 919
Free Coder Avatar asked Aug 31 '15 09:08

Free Coder


1 Answers

If you're working in a language without multiple inheritance, you should always favour composition over inheritance.

In languages without multiple inheritance (Java, C#, Visual Basic.NET), introducing one inheritance hierarchy automatically excludes you from all other, alternative inheritance hierarchies. In these languages, inheritance only locks you in.

With composition, you can do everything you can do with inheritance, as well as some things that you can't do with inheritance, such as, for example, simulating multiple inheritance.

Letting a class implement multiple interfaces essentially simulates multiple inheritance from any client's perspective.

Composing a class with multiple dependencies essentially solves the problem of 'inheriting' from multiple base classes for purposes of reusability.

Inheritance was originally included as a concept in OOP because OOP was originally described in terms of multiple inheritance. See e.g. Object-Oriented Software Construction, which explains OOP in terms of Eiffel - a programming language with multiple inheritance.

like image 92
Mark Seemann Avatar answered Dec 05 '22 00:12

Mark Seemann