Describe the difference between composition and inheritance.

12 minintermediateOOPcompositioninheritancedesign

Quick Answer

Inheritance is an 'is-a' relationship where a class derives from another class. Composition is a 'has-a' relationship where a class contains instances of other classes. Inheritance creates tight coupling and rigid hierarchies. Composition provides flexibility, loose coupling, and better testability. Favor composition over inheritance.

Detailed Answer

Inheritance ("is-a" relationship) - A class derives from another class and inherits its members.

Composition ("has-a" relationship) - A class contains instances of other classes as members.

Key Principle: Favor composition over inheritance for better flexibility and loose coupling.

Example:

// Inheritance Example (is-a relationship)
public class Vehicle
{
    public string Brand { get; set; }
    public void Start()
    {
        Console.WriteLine("Vehicle started");
    }
}

public class Car : Vehicle  // Car IS-A Vehicle
{
    public int NumberOfDoors { get; set; }
}

// Composition Example (has-a relationship)
public class Engine
{
    public int Horsepower { get; set; }
    
    public void Start()
    {
        Console.WriteLine("Engine started");
    }
}

public class Transmission
{
    public string Type { get; set; }
    
    public void ShiftGear()
    {
        Console.WriteLine("Gear shifted");
    }
}

public class Car2
{
    // Car HAS-A Engine
    private Engine engine;
    // Car HAS-A Transmission
    private Transmission transmission;
    
    public Car2()
    {
        engine = new Engine { Horsepower = 200 };
        transmission = new Transmission { Type = "Automatic" };
    }
    
    public void Start()
    {
        engine.Start();
        Console.WriteLine("Car is ready to drive");
    }
    
    public void Drive()
    {
        transmission.ShiftGear();
    }
}

// Why Composition is often better:
// 1. More flexible - can change components at runtime
// 2. No tight coupling
// 3. Avoids deep inheritance hierarchies
// 4. Easier to test and maintain