What is the difference between “IS -A” relationship and “HAS-A” relationship in Java?

We Are Going To Discuss About What is the difference between “IS -A” relationship and “HAS-A” relationship in Java? . So lets Start this Java Article.

What is the difference between “IS -A” relationship and “HAS-A” relationship in Java?

  1. What is the difference between “IS -A” relationship and “HAS-A” relationship in Java?

    An IS-A relationship is inheritance. The classes which inherit are known as sub classes or child classes. On the other hand, HAS-A relationship is composition.

  2. What is the difference between “IS -A” relationship and “HAS-A” relationship in Java?

    An IS-A relationship is inheritance. The classes which inherit are known as sub classes or child classes. On the other hand, HAS-A relationship is composition.

Solution 1

An IS-A relationship is inheritance. The classes which inherit are known as sub classes or child classes. On the other hand, HAS-A relationship is composition.

In OOP, IS-A relationship is completely inheritance. This means, that the child class is a type of parent class. For example, an apple is a fruit. So you will extend fruit to get apple.

class Apple extends Fruit {

}

On the other hand, composition means creating instances which have references to other objects. For example, a room has a table.
So you will create a class room and then in that class create an instance of type table.

class Room {

    Table table = new Table();

}

A HAS-A relationship is dynamic (run time) binding while inheritance is a static (compile time) binding.
If you just want to reuse the code and you know that the two are not of same kind use composition. For example, you cannot inherit an oven from a kitchen. A kitchen HAS-A oven.
When you feel there is a natural relationship like Apple is a Fruit use inheritance.

Original Author Neha Dadhich Of This Content

Solution 2

Foo is-a Bar:

public class Foo extends Bar{}

Foo has-a Bar

public class Foo {
    private Bar bar;
}

Original Author John Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment