Title here
Summary here
Concept | Description |
---|---|
Inheritance | One class inherits fields and methods from another (a “is-a” relationship). |
Composition | One class contains an instance of another class (a “has-a” relationship). |
They are both ways to reuse and organize code, but they serve different design goals.
class Engine {
void start() {
System.out.println("Engine started");
}
}
class Car extends Engine {
void drive() {
System.out.println("Car is driving");
}
}
Car
inherits start()
from Engine
.Car
is forced to be an Engine, which might not be accurate.class Engine {
void start() {
System.out.println("Engine started");
}
}
class Car {
private Engine engine = new Engine(); // Composition
void startCar() {
engine.start(); // Delegation
System.out.println("Car is ready to drive");
}
}
Car
has an Engine
, but is not an engine.Aspect | Inheritance | Composition |
---|---|---|
Relationship | is-a | has-a |
Coupling | Tight | Loose |
Flexibility | Low | High |
Reusability | In base-child chains | Through delegation |
Testing | Harder | Easier (swap components) |
Real-world modeling | Often forced | More accurate |
Favor composition over inheritance β (Effective Java, Item 18)
Inheritance is powerful but often overused. Composition leads to better encapsulation, flexibility, and maintainability.
You can even mix both:
class Engine {
void start() {
System.out.println("Engine starts...");
}
}
class Vehicle {
Engine engine = new Engine(); // Composition
void startVehicle() {
engine.start();
}
}
class Car extends Vehicle {
void drive() {
System.out.println("Car is driving...");
}
}
Here, Car
inherits from Vehicle
, and Vehicle
uses composition for Engine
.
Inheritance:
Bird
with a method fly()
.Sparrow
that adds method sing()
.Composition:
Speaker
with a method playMusic()
.Smartphone
that has a Speaker
object and a method playSong()
which delegates to playMusic()
.Questions to Answer (in comments or writeup):
Speaker
logic in the future?Speaker
in another class without changing it?Would you like to move next into Static Keyword, Final Keyword, or Association vs Aggregation vs Composition for a deeper dive into OOP relationships?