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 fromAnimal- 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 theCarclass holds an instance ofEngine- 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
| Relationship | Concept | Keyword/Usage | Example |
|---|---|---|---|
| IS-A | Inheritance | extends | Dog IS-A Animal |
| HAS-A | Composition | Create object inside class | Car HAS-A Engine |
