In Java, “IS-A” and “HAS-A” relationships are fundamental concepts related to Object-Oriented Programming (OOP). These relationships help in designing efficient and reusable code.
IS-A Relationship (Inheritance)
- The “IS-A” relationship represents inheritance in Java.
- It is achieved using extends (for classes) and implements (for interfaces).
- It defines a parent-child relationship where a subclass inherits the properties and behavior of a superclass.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Animal { void makeSound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void bark() { System.out.println("Dog barks"); } } public class Test { public static void main(String[] args) { Dog d = new Dog(); d.makeSound(); // Inherited from Animal d.bark(); // Defined in Dog } } |
In the above example:
Dog
IS-AAnimal
because it extends theAnimal
class.Dog
inherits themakeSound()
method fromAnimal
.
HAS-A Relationship (Composition)
- The “HAS-A” relationship represents composition or aggregation in Java.
- It means that one class contains an instance (object) of another class as a field.
- It is used when an object “has” another object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class Engine { void start() { System.out.println("Engine starting..."); } } class Car { Engine engine; // HAS-A relationship Car() { engine = new Engine(); } void startCar() { engine.start(); // Delegation System.out.println("Car is moving..."); } } public class Test { public static void main(String[] args) { Car myCar = new Car(); myCar.startCar(); } } |
In the above example:
Car
HAS-AEngine
because it contains an instance of theEngine
class.- This is composition, where
Car
depends onEngine
to function.
Differences Between IS-A and HAS-A
Feature | IS-A (Inheritance) | HAS-A (Composition) |
---|---|---|
Definition | Parent-child relationship | Whole-part relationship |
Implementation | extends (class) / implements (interface) |
Instance of another class as a field |
Code Reusability | High (inherits all properties) | Moderate (only required properties) |
Flexibility | Less flexible (tight coupling) | More flexible (loose coupling) |
Example | Dog extends Animal |
Car has an Engine |