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: • Inheritance represents an "is-a" relationship, whereas composition represents a "has-a" relationship. • Inheritance creates a strong dependency between parent and child classes. • Composition provides greater flexibility because components can be changed without affecting the entire hierarchy. • Inheritance is suitable when there is a clear parent-child relationship. • Composition is often preferred in modern application design because it promotes loose coupling and easier maintenance.

Example:

Inheritance: A Dog is an Animal.

Composition: A Car has an Engine.

Code Example:

// 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: • Relationship: Is-A • Coupling: Tight • Flexibility: Less flexible • Reusability: Through class hierarchy

Composition: • Relationship: Has-A • Coupling: Loose • Flexibility: More flexible • Reusability: Through object collaboration

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."