42

I am new to JAVA and just started learning "IS-A" and "HAS-A" relation but I didn't really get it.

What is the difference between "IS-A" and "HAS-A"?
When should I use "IS-A" and when should I use "HAS-A"?

Snostorp
  • 544
  • 1
  • 8
  • 14
Milan
  • 763
  • 3
  • 10
  • 18

2 Answers2

99

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.

Neha Dadhich
  • 1,043
  • 8
  • 5
  • Hi @Neha Dadhich According to this source https://www.geeksforgeeks.org/abstraction-in-java-2/ Has-a relation is Aggregation and not composition. Any explaination plz... – Sai Kiran Jun 10 '20 at 09:31
  • There is very little difference between Aggregation and Composition. Its a fine line and it does not really matter since it does not affect the implementation side of things. However, stick to one whenever you are making use of it/ @solokiran – TanDev Sep 03 '20 at 16:37
  • 1
    If one class has an instance of another class as its member,this is it always composition/aggregation?For example,in a stackoverflow a user class might have List, then does that make user has-a batch a composite relationship between user and batch? – rahul sharma Sep 28 '20 at 13:28
  • @Neha Dadhich The second part (HAS-A) of this answer is incorrect, HAS-A relationship is Aggregation and PART-OF is for Composition. – Davoud Apr 27 '21 at 10:03
  • as per my knowledge in. is a relation & has a relation both have a relation with other object but both are independent, but where as in composition child totally depends on the parent if a parent gets destroyed child destroy as well. in is a relation and has a relation both do not get destroyed if the other class get destoryed. Thanks – Atif AbbAsi Jun 21 '22 at 10:40
30

Foo is-a Bar:

public class Foo extends Bar{}

Foo has-a Bar

public class Foo {
    private Bar bar;
}
John
  • 3,458
  • 4
  • 33
  • 54