Skip to content

Java Composition (Strong HAS-A) 🏠

Mentor's Note: Composition is about Ownership. It means an object is made up of smaller parts. If you destroy the main object, the parts are destroyed too. They are "bound" together forever. 💡


🌟 The Scenario: The Modern House 🏠

Think about your home. - The Whole: The House. - The Parts: The Kitchen, the Bedroom, and the Bathroom. - The Bond: If the house is demolished, the kitchen doesn't survive on its own in the middle of the street. It is part of the house. ✅


🎨 Visual Logic: Strong Parts

classDiagram
    House *-- Kitchen
    House *-- Bedroom

    Car *-- Engine
    Car *-- Steering

    Computer *-- CPU
    Computer *-- RAM
(-- represents strong ownership)*


💻 Java Implementation: The Ownership Lab

1. The Car & Engine 🚗

Logic: A Car has an Engine. The engine belongs to that car.

class Engine {
    void start() { System.out.println("Engine Vroom! ⚙️"); }
}

class Car {
    // Composition: The Engine is created INSIDE the Car
    private final Engine engine;

    Car() {
        this.engine = new Engine(); 
    }

    void drive() {
        engine.start();
        System.out.println("Car is moving... 🏎️");
    }
}

2. The Personal Computer 💻

Logic: A Computer has a CPU.

class CPU {
    String model = "Intel i9";
}

class Computer {
    private CPU cpu = new CPU(); // Strong bond

    void showSpecs() {
        System.out.println("Powered by: " + cpu.model);
    }
}

3. The Human Body 🧠

Logic: A Human has a Heart.

class Heart {
    void beat() { System.out.println("Lubb-Dupp... ❤️"); }
}

class Human {
    private final Heart heart = new Heart();
}

📖 Composition vs. Inheritance

Feature Inheritance (IS-A) Composition (HAS-A)
Bond Permanent Family Assembly of Parts
Visibility Shares code with child Keeps parts Private
Flexibility Rigid Flexible (can swap parts)
Rule A Dog is an Animal A Car has an Engine

💡 Interview Tip 👔

"Interviewers often say: 'Favor Composition over Inheritance.' Why? Because Composition allows you to change the parts easily without breaking the whole system. It makes your code more modular!"


💡 Pro Tip: "Composition is like LEGO. You build complex things by snapping together smaller, specialized bricks."


📈 Learning Path