Skip to content

Java Composition (Strong HAS-A) 🏠¢

Prerequisites: Java Classes & Objects

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ΒΆ