IS-A and HAS-A Relationship in Java (OOP Concepts)
In Object-Oriented Programming (OOP), IS-A and HAS-A relationships define how classes interact with each other.
IS-A :
represents inheritence between classes.
eg: Audi is a car.
Defined using extends or implements keyword.
indicates that a subclass is a specialised version of its superclass.
HAS-A :
represents use of object of another class inside a class.
eg: Audi has a Horn
public class StaticDemo { class Car { void engine() { System.out.println("Car needs to have an engine."); } } class Audi extends Car { // ✅ Audi IS-A Car (Inheritance) static Horn h1 = new Horn(); // ✅ Audi HAS-A Horn (Composition) Audi() { h1.featureHorn(); // Calling featureHorn() inside constructor } @Override void engine() { System.out.println("Audi has refined diesel engine."); } } public static void main(String[] args) { StaticDemo staticDemo = new StaticDemo(); Audi a1 = staticDemo.new Audi(); // ✅ Audi IS-A Car (creating Audi object) a1.engine(); // ✅ Audi HAS-A Horn (using static Horn instance) Audi.h1.featureHorn(); // Output: pow pow } } // Separate class for Horn class Horn { void featureHorn() { System.out.println("pow pow"); } }
🔹 Explanation of example:
IS-A Relationship (Inheritance)
Audi extends Car
→Audi IS-A Car
Audi
inherits behavior fromCar
(engine()
method).
HAS-A Relationship (Composition)
Audi
HAS-AHorn
instance (static Horn h1
).This means
Audi
contains aHorn
but does not inherit from it.