IS-A and HAS-A relationship

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.

In the above example:

  • Dog IS-A Animal because it extends the Animal class.
  • Dog inherits the makeSound() method from Animal.

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.

In the above example:

  • Car HAS-A Engine because it contains an instance of the Engine class.
  • This is composition, where Car depends on Engine 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