What is the difference between composition and inheritance?
Answer
Inheritance ("is-a" relationship) creates a hierarchical relationship where a subclass inherits from a parent. Composition ("has-a" relationship) builds complex objects by containing references to simpler objects. Inheritance example: class Vehicle { void startEngine() { /* ... */ } } class Car extends Vehicle { // Car IS-A Vehicle } // Problem: what if Car needs GPS, which isn't a Vehicle? // Can't inherit from both Vehicle and GPSDevice. Composition example: class Engine { void start() { System.out.println("Engine started"); } void stop() { System.out.println("Engine stopped"); } } class GPS { String getLocation() { return "Lat: 40.7128, Long: -74.0060"; } } class Car { private Engine engine; // Car HAS-A Engine private GPS gps; // Car HAS-A GPS public Car() { this.engine = new Engine(); this.gps = new GPS(); } public void start() { engine.start(); } public String navigate() { return gps.getLocation(); } }. Why "Favor composition over inheritance" (GoF principle): (1) Composition is more flexible — can change components at runtime; (2) No fragile base class problem — parent changes don't unexpectedly break children; (3) Avoids deep inheritance hierarchies (hard to understand, brittle); (4) Easier to test — inject mock components; (5) Better encapsulation — don't expose parent's protected internals. When to use inheritance: genuine "is-a" relationship, need polymorphism, sharing a common interface, when subclass truly IS a specialization of parent. The Liskov Substitution Principle (LSP) is the litmus test — if child can't be used everywhere parent is, don't inherit.