OOP.What do the expressions “is” and “has” mean in terms of OOP principles?

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 of Animal ➡️ Dog extends Animal
  • Car is a type of Vehicle ➡️ Car extends Vehicle
  • Rectangle is a type of Shape ➡️ Rectangle extends Shape

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 a Engine ➡️ Car has a field of type Engine
  • Order has a Customer ➡️ Order has a field of type Customer
  • Computer has a CPU ➡️ Computer has a field of type CPU

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 relationshipSpecializationOwnership/Containment
ExampleDog is an AnimalCar has an Engine
FlexibilityTight coupling (fragile hierarchies)Loose coupling (can replace parts easily)
Code change impactChanges to parent affect all childrenChanges to part (Engine) do not affect Car directly
Preferred forModeling typesModeling 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).
This entry was posted in Без рубрики. Bookmark the permalink.