2

I've read that composition can be used instead of inheritance and all programs using inheritance can be transformed to a program using composition and vice-versa. I've also read that using composition is better than using inheritance.

Even though I've read the facts, I don't understand how and why this is true. I can't even think of an example to demonstrate this.

Could someone please help me clear out my doubts. It would be very much appreciated if you could use an example too.

  • 1
    Does this answer your question? [Prefer composition over inheritance?](https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance) – funky Mar 03 '21 at 10:07
  • 1
    *"I've also read that using composition is better than using inheritance."* - As a general statement that is not true. Or at least, a matter of opinion. – Stephen C Mar 03 '21 at 10:09
  • 1
    The possibility to convert one approach into the other tells us nothing about the question which one is better in a given situation. So, you have to decide whether an "is-a" relationship suits better than a "has" relationship. – Ralf Kleberhoff Mar 03 '21 at 10:35

1 Answers1

1

Inheritance is is relationship. E.g., teacher is human.

Composition is has relationship. E.g., pizza has tomato.

Inheritance makes tight coupling between your classes such as Child class and Parent class. So making changes can be a reason to make changes in all inherited classes.

Composition is very effective when you want to define what behavior should be used at the compile time and run time. You can create an interface and give realization of this interface at at the compile time and run time.

Inheritance is very good when we reuse methods and we want to override them. However, you can use composition to achieve this goal.

There is a nice article about Composition over inheritance. It says:

Composition over inheritance (or composite reuse principle) in object-oriented programming (OOP) is the principle that classes should achieve polymorphic behavior and code reuse by their composition (by containing instances of other classes that implement the desired functionality) rather than inheritance from a base or parent class.

An example of inheritance:

public class Human
{
    string Title;
    string Name;
    int Age;
}

public class Teacher : Human
{
    int Salary;
    string Subject;
}

An example of composition:

public class Human
{
    string Title;
    string Name;
    int Age;
}


public class Teacher
{
    private Human _human;

    public Teacher(Human human)
    {
        _human = human;
    }
}
StepUp
  • 30,747
  • 12
  • 76
  • 133