What is IS-A and HAS-A relationship in java

IS-A and HAS-A relationship in java :

IS-A relationship :

IS-A relationship is based on class inheritance or interface implementation. You can say that “this thing is a type of that
thing”.
Example :

Suppose you have a class Vehicle and another class Car extending Vehicle class. So you can say that a Car is a
Vehicle i.e. Car IS-A Vehicle.

Syntax :


public class Vehicle{
//some code here!
}

public class Car extends Vehicle{
//some code here!
}

 

HAS-A relationship :

It is based on usage rather than inheritance. Suppose a class Vehicle and other class Car which extending Vehicle class and
in class Car contain a reference variable of class Vehicle like below..


public class Vehicle{
//some code here!
}

public class Car{
private Break mybreak;
//some logic here!
}

In above code class Car has an instance variable type of Break. So you can say ..
Car HAS-A Break.

Note : HAS-A relationship allows us to design classes that follow good OO practices which help reduce bugs.

Advertisements