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."