Notes – What is Is-A and Has-A Relationship in Java

In Object-Oriented Programming, understanding how classes relate to each other is crucial. Java uses IS-A and HAS-A relationships to define these connections between classes.


What is IS-A Relationship?

  • IS-A represents Inheritance.
  • It means one class is a type of another class.

Syntax:

class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

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

Explanation:

  • Dog IS-A Animal โ†’ because it inherits from Animal
  • This relationship is established using the extends keyword.

Benefits of IS-A:

  • Code reusability
  • Method overriding (Polymorphism)
  • Simplifies code structure

What is HAS-A Relationship?

  • HAS-A means one class contains an object of another class.
  • This represents composition or aggregation.

Syntax:

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

class Car {
Engine eng = new Engine(); // Car HAS-A Engine

void drive() {
eng.start();
System.out.println("Car is driving.");
}
}

Explanation:

  • Car HAS-A Engine โ†’ because the Car class holds an instance of Engine
  • Used to build complex objects from smaller ones

Benefits of HAS-A:

  • Promotes code modularity
  • Supports better system design
  • Allows flexible object interaction

Quick Comparison Table


RelationshipConceptKeyword/UsageExample
IS-AInheritanceextendsDog IS-A Animal
HAS-ACompositionCreate object inside classCar HAS-A Engine