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 interface IEngine
{
string Name { get; }
decimal Volume { get; }
}
public class Engine : IEngine
{
public string Name => "Foo Engine";
public decimal Volume => 4;
}
public class Car
{
private IEngine _engine;
public Car(IEngine _engine)
{
_engine = engine;
}
}