Back to series
· 9 min read

Composition vs. Inheritance


1. Basic Concepts of Composition and Inheritance

Composition and inheritance can both achieve code reuse, but they express different design relationships.

  • Inheritance: Reuse the properties and methods of a parent class by establishing a type relationship between the parent class and the subclass.
  • Composition: Have one object hold references to other objects, combining the capabilities of multiple objects into more complex functionality.

The core differences between the two are:

Dimension Inheritance Composition
Core relationship is-a (is a kind of) has-a (has one)
Code reuse Inherit the parent class implementation Delegate to internal objects
Type relationship Establishes a subtype relationship No type relationship required
Coupling Usually higher Usually lower
Extension approach Extend or override the parent class Replace or add internal components
Flexibility Constrained by the inheritance hierarchy Can compose different implementations at runtime
Source of polymorphism Subtype polymorphism Interface polymorphism, delegation, etc.
Main risk Complex inheritance hierarchy, fragile parent class Complex object collaboration and dependency management

Note: Composition is not the same as simply declaring a field of another class inside a class. Meaningful composition usually includes a clear division of responsibilities and collaboration or delegation relationships between objects.

2. Inheritance Mechanism

2.1 Basic Structure of Inheritance

Inheritance allows a subclass to obtain inheritable members defined by the parent class and, on that basis, add or modify behavior.

Take Java as an example:

class Animal {
    protected String name;

    public Animal(String name) {
        this.name = name;
    }

    public void eat() {
        System.out.println(name + " is eating");
    }
}

class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }

    public void bark() {
        System.out.println(name + " is barking");
    }
}

Usage:

Dog dog = new Dog("Buddy");

dog.eat();
dog.bark();

Dog inherits the accessible members of Animal while adding its own behavior.

From the perspective of type relationships:

Animal animal = new Dog("Buddy");
animal.eat();

Dog is a subtype of Animal, so a Dog object can be used wherever an Animal is required.

2.2 How Inheritance Works

Inheritance is not only a code reuse mechanism; it also affects the type system, method dispatch, and object initialization.

Taking Java as an example, its basic structure can be abstracted as:

flowchart TB
    A["Define parent class Animal"] --> B["Define subclass Dog"]
    B --> C["Establish extends inheritance relationship"]
    C --> D["Subclass obtains inheritable members"]
    D --> E["Subclass adds or overrides methods"]
    E --> F["Create subclass object"]
    F --> G["Execute parent class construction process"]
    G --> H["Execute subclass construction process"]
    H --> I["Object can be referenced through parent class type"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style I fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Three concepts need to be distinguished:

  1. Member inheritance: A subclass can use the members of its superclass that are permitted to be inherited and accessed.
  2. Subtyping relationship: A subclass object can be used in any context that requires the superclass type.
  3. Method overriding: A subclass provides its own implementation of an inherited method, and at runtime the implementation may be selected through dynamic dispatch based on the actual object type.

These three concepts are interrelated, but they are not entirely equivalent.

2.3 Method Overriding and Dynamic Dispatch

Inheritance is often used together with runtime polymorphism.

class Animal {
    public void makeSound() {
        System.out.println("Unknown sound");
    }
}

class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Woof");
    }
}

class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Meow");
    }
}

Invocation:

Animal animal = new Dog();
animal.makeSound();

Output:

Woof

Here:

  • The declared type of the reference is Animal.
  • The actual type of the object is Dog.
  • When an overridable instance method is invoked, Java selects the implementation based on the actual object type.

This mechanism is called dynamic method dispatch.

Note that Java's static methods, field access, and constructors do not follow the ordinary instance-method rules of dynamic dispatch. Whether a method can be overridden is also constrained by modifiers such as private, static, and final.

2.4 Main Problems with Inheritance

Inheritance can reduce duplicated code, but it may also introduce strong structural coupling.

Problem 1: Changes to the superclass affect subclasses

Once the internal implementation of a superclass changes, it may affect multiple subclasses.

For example, if a superclass changes the behavior of a method that subclasses depend on, subclasses that previously worked correctly may start to fail.

Problem 2: The inheritance hierarchy keeps expanding

As a system continually accumulates business variations, a large number of specialized subclasses tend to appear:

Animal
├── FlyingAnimal
│   ├── FlyingBird
│   └── FlyingInsect
└── SwimmingAnimal
    ├── SwimmingFish
    └── SwimmingMammal

If an object has several capabilities at once, such as both flying and swimming, a single-inheritance hierarchy cannot express this naturally.

Problem 3: Subclasses are constrained by the superclass design

A subclass must obey the behavioral contract defined by its superclass. If the superclass is poorly designed, the subclass may be forced to inherit behavior it does not need, or to override the superclass's default implementation in order to avoid it.

Problem 4: An inheritance relationship may violate the Liskov Substitution Principle

The Liskov Substitution Principle (LSP) requires that objects of a subtype should be able to replace objects of the supertype without breaking the original correctness of the program.

For example:

class Rectangle {
    protected int width;
    protected int height;

    public void setWidth(int width) {
        this.width = width;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public int area() {
        return width * height;
    }
}

If Square extends Rectangle and overrides both setters to keep the sides equal:

class Square extends Rectangle {
    @Override
    public void setWidth(int width) {
        this.width = width;
        this.height = width;
    }

    @Override
    public void setHeight(int height) {
        this.width = height;
        this.height = height;
    }
}

The caller may assume that width and height can be modified independently:

Rectangle rectangle = new Square();

rectangle.setWidth(5);
rectangle.setHeight(10);

System.out.println(rectangle.area());

Based on the expected behavior of a rectangle, the caller may think the area should be 50, but the actual result is 100.

The problem is not the mathematical definition of a square, but that the subclass changes the behavioral contract of its superclass.

This shows that a special relationship in mathematics is not necessarily suitable for direct translation into an inheritance relationship in software design.

III. The Composition Mechanism

3.1 The Basic Structure of Composition

Composition organizes different responsibilities together by having an object hold other objects.

For example, a car object can contain an engine object:

class Engine {
    public void start() {
        System.out.println("Engine started");
    }
}

class Car {
    private final Engine engine;

    public Car(Engine engine) {
        this.engine = engine;
    }

    public void start() {
        engine.start();
        System.out.println("Car started");
    }
}

Usage:

Engine engine = new Engine();
Car car = new Car(engine);

car.start();

Here:

  • Engine is responsible for engine-related behavior.
  • Car is responsible for the overall behavior of the car.
  • Car uses engine capabilities by holding an Engine object.

Car is not a kind of Engine; rather, it has an Engine.

3.2 Delegation Mechanism

Composition usually achieves behavior reuse through delegation.

Delegation means that one object assigns a specific task to another object to complete.

For example:

interface PaymentProcessor {
    void pay(double amount);
}

class AlipayProcessor implements PaymentProcessor {
    @Override
    public void pay(double amount) {
        System.out.println("Alipay: " + amount);
    }
}

class WechatProcessor implements PaymentProcessor {
    @Override
    public void pay(double amount) {
        System.out.println("Wechat Pay: " + amount);
    }
}

class OrderService {
    private final PaymentProcessor paymentProcessor;

    public OrderService(PaymentProcessor paymentProcessor) {
        this.paymentProcessor = paymentProcessor;
    }

    public void checkout(double amount) {
        paymentProcessor.pay(amount);
    }
}

Usage:

PaymentProcessor processor = new AlipayProcessor();

OrderService orderService = new OrderService(processor);
orderService.checkout(100);

OrderService does not need to know the concrete payment implementation; it depends only on the PaymentProcessor abstraction.

If the payment method needs to be switched, another implementation can be injected:

PaymentProcessor processor = new WechatProcessor();

OrderService orderService = new OrderService(processor);
orderService.checkout(100);

This reflects an important advantage of composition: business objects can depend on abstractions instead of being bound to a specific implementation.

3.3 Execution Flow of Composition

flowchart TB
    A["Define capability interface"] --> B["Implement different components"]
    B --> C["Create business object"]
    C --> D["Inject component dependencies"]
    D --> E["Business object receives request"]
    E --> F["Call component interface"]
    F --> G["Component executes concrete behavior"]
    G --> H["Return execution result"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

3.4 Composition and Dependency Injection

Composition is often used together with dependency injection (DI).

The core idea of dependency injection is: an object is not responsible for creating all of its dependencies; instead, the dependency objects it needs are provided from the outside.

Common injection approaches:

Injection approach Description Characteristics
Constructor injection Dependencies are passed in through the constructor Dependencies are explicit, making it easy to guarantee object integrity
Setter injection Dependencies are set through setter methods Suited to optional or changeable dependencies
Field injection Dependencies are injected directly into object fields Concise code, but the dependency relationships are not explicit enough
Method parameter injection Dependencies are passed in when a method is called Suited to dependencies used only in a single operation

Example of constructor injection:

class NotificationService {
    private final MessageSender sender;

    public NotificationService(MessageSender sender) {
        this.sender = sender;
    }
}

It clearly expresses the dependencies required to create the object, and together with a final field, it keeps the dependency reference unchanged after construction is complete.

But note the following:

  • Composition does not require the use of a dependency injection framework.
  • Dependency injection is a technique for supplying dependencies; it is not composition itself.
  • Frameworks such as Spring can manage object creation, dependency injection and lifecycle, but these capabilities are not prerequisites for the composition mechanism to hold.

IV. The Core Differences Between Composition and Inheritance

4.1 is-a and has-a

This is the most common way to distinguish inheritance from composition.

Inheritance expresses:

Dog is an Animal

Composition expresses:

Car has an Engine

However, you cannot decide whether inheritance should be used based merely on the “is a” phrasing in natural language.

Software design also needs to consider:

  • Whether the subtype satisfies the behavioral contract of the parent type.
  • Whether the parent class provides a stable and reasonable abstraction.
  • Whether the subclass genuinely needs the parent class's behavior and constraints.
  • Whether there is a clearer way to compose responsibilities.

4.2 Compile-time relationships and runtime flexibility

Inheritance relationships are usually determined when the type is defined.

class Dog extends Animal {
}

The inheritance relationship between Dog and Animal is determined by the type declaration.

Composition relationships, by contrast, can be configured through how the dependent object is created and injected.

class OrderService {
    private final PaymentProcessor processor;

    public OrderService(PaymentProcessor processor) {
        this.processor = processor;
    }
}

Different instances can hold different implementations of PaymentProcessor.

As a result, composition more easily supports runtime strategy replacement and dependency configuration.

That said, inheritance does not mean that all behavior can only be determined at compile time. Virtual methods in an inheritance hierarchy can likewise support runtime polymorphism.

4.3 Reusing implementations vs. reusing abstractions

Inheritance typically reuses both the parent class's implementation and the type relationship.

Composition can reuse only the capability provided by a certain object, without needing to inherit its type.

For example:

class Logger {
    public void log(String message) {
        System.out.println(message);
    }
}

class UserService {
    private final Logger logger;

    public UserService(Logger logger) {
        this.logger = logger;
    }

    public void createUser() {
        logger.log("User created");
    }
}

UserService uses the functionality of Logger, but it is not a kind of Logger.

This design avoids forcing unrelated types into the same inheritance hierarchy.

V. The Principle of Favoring Composition over Inheritance

5.1 The meaning of the principle

“Favor composition over inheritance” is an important rule of thumb in object-oriented design.

It does not demand abandoning inheritance entirely; rather, it emphasizes:

When inheritance is not a necessary condition for expressing a genuine subtype relationship, give priority to achieving code reuse and behavior extension through composition.

The main reasons are as follows:

  1. Lower coupling: Business objects do not have to depend on the parent class's internal implementation.
  2. Clear responsibilities: Different components are responsible for different functions.
  3. Flexible extension: Components can be replaced without endlessly adding subclasses.
  4. Easier testing: Mock objects or test doubles can be injected.
  5. Avoiding inheritance hierarchy bloat: Multiple capabilities can be composed independently.

5.2 Class explosion caused by inheritance

Suppose a system needs to represent different types of roles:

  • Administrator
  • Regular user
  • Guest

Each role in turn has different capabilities:

  • Log in
  • Pay
  • Export data
  • Manage users

If you keep combining roles and capabilities through inheritance, it is very easy to end up with a large number of subclasses.

For example:

User
├── AdminUser
├── GuestUser
├── PayingUser
├── ExportingUser
├── AdminPayingUser
└── AdminExportingUser

As roles and capabilities increase, the number of classes and the depth of the inheritance hierarchy become difficult to maintain.

Using composition, roles and capabilities can be separated:

interface Permission {
    void execute();
}

class PaymentPermission implements Permission {
    @Override
    public void execute() {
        System.out.println("Payment allowed");
    }
}

class ExportPermission implements Permission {
    @Override
    public void execute() {
        System.out.println("Export allowed");
    }
}

class User {
    private final List<Permission> permissions;

    public User(List<Permission> permissions) {
        this.permissions = permissions;
    }

    public void executePermissions() {
        for (Permission permission : permissions) {
            permission.execute();
        }
    }
}

Different users can hold different permission components.

This design separates user identity from permission capabilities, avoiding the creation of a large number of subclasses for different combinations of capabilities.

5.3 Strategy Pattern: A Typical Application of Composition

The Strategy Pattern is a typical application of the composition idea.

It encapsulates variable algorithms as independent strategies, so that a client can switch between different strategies.