Sobes.tech
Junior

What are the differences between inheritance and composition in object-oriented programming?

sobes.tech AI

Answer from AI

Inheritance:

  • The "is-a" relationship.
  • A subclass inherits fields and methods from the parent class.
  • Used to create specialized versions of existing classes.
  • Can lead to rigid hierarchies and issues with multiple inheritance.

Composition:

  • The "has-a" relationship.
  • A class contains instances of other classes as its fields.
  • Delegates task execution to contained objects.
  • Provides flexibility and the ability to replace components.

Example in Java:

// Inheritance
class Vehicle { // Base class
    void start() { /* ... */ }
}

class Car extends Vehicle { // Inherits from Vehicle
    // Car-specific methods
}

// Composition
class Engine { // Component
    void start() { /* ... */ }
}

class AnotherCar { // Class using composition
    private Engine engine; // Contains an Engine instance

    AnotherCar(Engine engine) {
        this.engine = engine;
    }

    void start() {
        engine.start(); // Delegation
    }
}

Differences can be summarized in a table:

Criterion Inheritance Composition
Relationship "is-a" "has-a"
Rigidity More rigid More flexible
Reusability Through class hierarchy Through object instances
Behavior change Method overriding Replacing contained objects
Application Specialization, extending functionality Aggregation, building from parts

Composition is generally preferred over inheritance in most cases for achieving greater flexibility and reducing dependencies between classes.