Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between IS -A relationship and HAS-A relationship in Java? [duplicate]

Tags:

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"?

like image 550
Milan Avatar asked Mar 22 '16 18:03

Milan


1 Answers

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.

like image 166
Neha Dadhich Avatar answered Sep 27 '22 23:09

Neha Dadhich