What is the Decorator pattern and how does it differ from inheritance?

The Decorator pattern adds behavior to individual objects dynamically at runtime by wrapping them, whereas inheritance adds behavior to an entire class hierarchy at compile time. Decorator targets specific instances; inheritance targets every instance of a subclass.

Key Points

Example

Instead of creating subclasses like EspressoWithMilk and EspressoWithMilkAndSugar for every combination of add-ons, a Decorator lets you wrap a plain Espresso object with a MilkDecorator and a SugarDecorator only when needed, on only the instances that need them.

public class DecoratorVsInheritance {

    interface Coffee { String description(); int cost(); }

    static class Espresso implements Coffee {
        public String description() { return "Espresso"; }
        public int cost() { return 120; }
    }

    static abstract class AddOn implements Coffee {
        protected final Coffee inner;
        AddOn(Coffee inner) { this.inner = inner; }
    }

    static class MilkDecorator extends AddOn {
        MilkDecorator(Coffee c) { super(c); }
        public String description() { return inner.description() + ", milk"; }
        public int cost() { return inner.cost() + 30; }
    }

    static class SugarDecorator extends AddOn {
        SugarDecorator(Coffee c) { super(c); }
        public String description() { return inner.description() + ", sugar"; }
        public int cost() { return inner.cost() + 10; }
    }

    public static void main(String[] args) {
        // No EspressoWithMilkAndSugar subclass needed: combine at runtime
        Coffee plain = new Espresso();
        Coffee full = new SugarDecorator(new MilkDecorator(new Espresso()));
        System.out.println(plain.description() + " = Rs " + plain.cost());
        System.out.println(full.description() + " = Rs " + full.cost());
    }
}

Output

Espresso = Rs 120

Espresso, milk, sugar = Rs 160

Common Mistakes

Follow-up Questions

Interview Tip

A concise interview answer is

Decorator adds behavior to specific object instances at runtime through composition, while inheritance adds behavior to an entire class at compile time. Decorator avoids the rigid, exploding class hierarchies you get when you try to cover every feature combination with subclasses.

Last updated: 11 November 2026

Previous question: How would you implement the Composite pattern in Java?

Next question: How would you implement the Decorator pattern in Java?

More Java Design Patterns interview questions

All Java Design Patterns questions