What is the difference between inheritance and composition?

Inheritance and composition are two object-oriented techniques used to achieve code reuse. Inheritance allows a class to acquire properties and behaviors from another class, while composition builds a class by combining objects of other classes. Composition is generally considered more flexible because it promotes loose coupling.

Key Points

Example

Inheritance

A Dog is an Animal.

Composition

A Car has an Engine.

// Inheritance Example

class Animal {

    void eat() {
        System.out.println("Animal is eating");
    }
}

class Dog extends Animal {

    void bark() {
        System.out.println("Dog is barking");
    }
}


// Composition Example

class Engine {

    void start() {
        System.out.println("Engine Started");
    }
}

class Car {

    private Engine engine = new Engine();

    void startCar() {
        engine.start();
    }
}

Comparison

Inheritance

Composition

Interview Tip

A concise interview answer is

Inheritance is an 'is-a' relationship where a class extends another class and reuses its behavior. Composition is a 'has-a' relationship where a class contains objects of other classes. Composition is generally preferred because it provides better flexibility, loose coupling, and easier maintenance.

Last updated: 16 July 2026

Previous question: Why is multiple inheritance not supported in Java?

Next question: Discuss the principle of "composition over inheritance". Provide an example where this principle should be applied in Java application design.

More Core Java - Level II interview questions

All Core Java - Level II questions