oop

11. Composition vs Inheritance: 'HAS-A' vs 'IS-A'

Analyze the code, write your predicted output, and then reveal the solution.

Scenario

"Favor Composition over Inheritance" is a core design principle. This practice shows how to reuse code by having an object of another class as a field, rather than extending it.

Code Block
class Engine { void start() { System.out.println("Engine roaring..."); } } // Inheritance (Is-A) - Bad if we just want the engine's behavior // class Car extends Engine { } // Composition (Has-A) - Better class Car { private final Engine engine; // Composition Car(Engine engine) { this.engine = engine; } void drive() { engine.start(); System.out.println("Car is moving"); } } public class Main { public static void main(String[] args) { Engine e = new Engine(); Car myCar = new Car(e); myCar.drive(); } }
Take Your Shot
Predicted Output

Type exactly what you think will be printed in the console.

11. Composition vs Inheritance: 'HAS-A' vs 'IS-A' | DevExCode