Free Coder
Free Coder

Reputation: 487

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?

Upvotes: 14

Views: 7706

Answers (3)

Carbine
Carbine

Reputation: 7903

In short,

If it is a is-a relationship use inheritance. Use composition when it is a has-a relationship.

Inheritance is perfectly fine as long as nothing changes. But You will face a lot of problems with inheritance when you tend to extend/modify the behaviour of the classes later.

You tend to break your initial assumption and you need to make changes in lot of places. If you use composition you can avoid all these fixing.

Upvotes: 9

Atul
Atul

Reputation: 2711

Rather than change, maintainability, etc, I think the core concept matters. Does Is A relationship seem better than a Has A relationship in a given situation?

A recommended reading: Gang Of Four's discussion about Type, Interface, OOP, etc before they begin discussion about patterns.

Also take a look at: Composition vs. Inheritance: How to Choose?

Upvotes: 1

Mark Seemann
Mark Seemann

Reputation: 233150

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.

Upvotes: 18

Related Questions