Relationship Types in Java : IS-A vs HAS-A

There are two ways to reuse the already written classes: Either we can inherit the already written classes or make objects of already written classes inside our class. So, these two ways of code reuse form the basis of following two types of relationships:

  • IS-A relationship : based on inheritance.
  • HAS-A relationship : based on composition i.e creating objects of other classes inside a class.

Note: It is a general concept applicable to all the languages and not specific to Java.

IS-A vs HAS-A relationship in Java
IS-A vs HAS-A relationship

1. IS-A relationship

It is based on inheritance. We use extends keyword to extend the functionalities of the parent class. In the process, a sub class inherits all the non-private properties and functionalities of the parent class.

Inheritance is an IS-A relationship because you can use parent class reference to refer to the child class object. For example: from the diagram above, we can use the Machine class reference to refer an object of the Computer class. So, Computer is-a Machine. Similarly Mango is-a Fruit, Rose is-a Flower etc.

Interfaces also form the IS-A relationship with the classes that implement them. We use implements keyword to implement an Interface.


2. HAS-A relationship

When we use reference variables of other classes inside another class then it forms HAS-A relationship. For example, we can use already written CPU class inside the Computer class. So A computer has-a CPU. Similarly, A House has-a Bathroom, A Car has-an Engine etc.


3. An Example

Let’s have an example where we use both the IS-A and HAS-A relationship. We will convert the diagram above into code.

Output:

 


Both Inheritance and Composition are ways of code reuse. Each one of them is suited in different situations. But note that Inheritance is a static concept while Composition can be used dynamically.