Java

IS-A and HAS-A Relationship in Java

By Utility Zone ยท 2026-02-16T14:35:19.398712

1. IS-A Relationship (Inheritance)

Definition

An IS-A relationship represents inheritance in Java.
It means one class is a specialized version of another class.

Syntax

class Child extends Parent

Example

class Animal {
    void eat() {
        System.out.println("Eating...");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Barking...");
    }
}

Here:

Dog IS-A Animal.

  • Dog inherits behavior from Animal.
  • Enables method overriding and runtime polymorphism.

When to Use IS-A

  • When there is a true hierarchical relationship.
  • When polymorphism is required.
  • Example:
    • Car IS-A Vehicle
    • Manager IS-A Employee

2. HAS-A Relationship (Composition)

Definition

A HAS-A relationship represents composition.
It means one class contains another class as a member.

Example

class Engine {
    void start() {
        System.out.println("Engine started");
    }
}

class Car {
    private Engine engine = new Engine();  // HAS-A relationship

    void drive() {
        engine.start();
        System.out.println("Car is moving");
    }
}

Here:

Car HAS-A Engine.

Car is not an Engine.
Car contains an Engine.

When to Use HAS-A

  • When building modular and flexible designs.
  • When avoiding tight coupling.
  • When following the principle:
    Favor Composition over Inheritance.

Examples: - Car HAS-A Engine - House HAS-A Room - Employee HAS-A Address


Key Differences

IS-A HAS-A


Inheritance Composition Uses extends Uses object reference Strong coupling More flexible Supports polymorphism Encourages modular design


Design Insight

Bad Design:

class Car extends Engine  // Incorrect

Good Design:

class Car {
    Engine engine;
}

IS-A builds hierarchy.
HAS-A builds modular structure.