The expressions “is” and “has” are super important when designing object-oriented systems. They help you decide how classes and objects relate to each other — and this directly ties into Inheritance and Composition, two fundamental OOP techniques.
✅ “is-a” Relationship (Inheritance)
Meaning
If you can say Object A is a type of Object B, then A should inherit from B.
This is the foundation of inheritance — a child class inherits from a parent class because it is a specialized version of the parent class.
Examples
Dog
is a type ofAnimal
➡️Dog
extendsAnimal
Car
is a type ofVehicle
➡️Car
extendsVehicle
Rectangle
is a type ofShape
➡️Rectangle
extendsShape
Code Example
class Animal {
void eat() { System.out.println("This animal eats food."); }
}
class Dog extends Animal {
void bark() { System.out.println("Woof Woof"); }
}
✅ Dog
is-a Animal
, so inheritance is correct here.
✅ “has-a” Relationship (Composition / Aggregation)
Meaning
If you can say Object A has a type of Object B, then A should have a field of type B.
This is the foundation of composition — one object contains or depends on another object, rather than inheriting from it.
Examples
Car
has aEngine
➡️Car
has a field of typeEngine
Order
has aCustomer
➡️Order
has a field of typeCustomer
Computer
has aCPU
➡️Computer
has a field of typeCPU
Code Example
class Engine {
void start() { System.out.println("Engine starting..."); }
}
class Car {
private Engine engine = new Engine(); // has-a relationship
void startCar() {
engine.start();
System.out.println("Car started.");
}
}
✅ Car
has-a Engine
, so composition is correct here.
🔥 Key Difference
Concept | “is-a” (Inheritance) | “has-a” (Composition) |
---|---|---|
Type of relationship | Specialization | Ownership/Containment |
Example | Dog is an Animal | Car has an Engine |
Flexibility | Tight coupling (fragile hierarchies) | Loose coupling (can replace parts easily) |
Code change impact | Changes to parent affect all children | Changes to part (Engine) do not affect Car directly |
Preferred for | Modeling types | Modeling parts or dependencies |
💬 Rule of Thumb
- Use “is-a” (inheritance) only if there’s a clear, permanent type relationship.
- Use “has-a” (composition) for flexible containment or dependencies — this is often preferred in modern design (Composition over Inheritance).