What is IS-A Relationship in Java?

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

In OOPs, the IS-A relationship corresponds to the concept of inheritance. For instance, a mango is a fruit, a phone is a device.

The reason for using the IS-A relationship in java are as follows:

  • Reducing redundancy
  • Code reusability
  • IS-A relationship in java can be achieved by using the keyword ‘extends’ in the code.
  • It is used for avoiding any kind of redundancy in the code and to reuse the class and methods in the program.
  • The IS-A relationship is unidirectional which means that mango is a fruit but not all fruits are mango.
  • IS-A relationship is also known to be tightly coupled which means that by changing one entity, other entity will also be changed.

How to Achieve an IS-A Relationship?

IS-A relationship in Java can be achieved by extending a class or interface by using the keyword ‘extends’.

Is a relationship one

Let’s understand this clearly by taking an example

Is a relationship two

In the given image, the class Mango extends a class Fruit. This means that Fruit is a parent class of Mango and the class Mango is said to have IS-A relationship with class Fruit. Hence we say that Mango IS-A Fruit.

Examples of IS-A relationship in Java

Implementation of IS-A relationship

  • Class Fruit has a field called fruitName
  • Class Mango extends the class Fruit to get its functionalities.
  • Because Fruit is a parent class, it can store a reference of an instance of class Mango. The advantage of it is that the code isn't duplicated.

Program to implement IS-A relationship in Java

Output:

Explanation:

  • It defines a parent class Fruit and a child class Mango.
  • The Fruit class has a field fruitName and two methods: setFruitName and getFruitName.
  • The Mango class is a child class of Fruit. It has an additional private field shape and a constructor that calls the constructor of the parent class using the super keyword. It also has a method getFruitShape that returns the name of the fruit and its shape.
  • The Main class contains a main method that creates an instance of Mango called fruit with the shape "Pear-Shaped". It then prints out the name and shape of the fruit using the getFruitName and getFruitShape methods.

Learn More

Conclusion

Here are a few key takeaways from this blog.

  • In OOPs, the IS-A relationship corresponds to the concept of inheritance. For instance, a mango is a fruit, a phone is a device.
  • The reason for using the IS-A relationship in java are as follows:
    • Reducing redundancy
    • Code reusability
  • IS-A relationship in java can be achieved by extending a class or interface by using the keyword ‘extends’.