IS-A Vs HAS-A Relationship in Java

Connect with

Oracle Java
IS-A (Inheritance) relationship and HAS-A (composition) relationship is the one of the important interview question in core java, design consideration and mostly asked to experience developer to check whether he/she knows basic of design consideration or not. In the object oriented world, re-use is the basic concept and technique either via IS-A (inheritance) or HAS-A ( composition) relationship.

The fundamental of IS-A is referring to inheritance, it means when inheriting anything from super class, you can say IS-A applies. e.g. Is-a means “SUVCar is a type of Car”, it means, SUVCar.java inherits properties from Car.java (either by extends or implements keyword).

Has-a means “Car has Engine” , and strongly associated, it means Engine object is composed inside the class Car.

What is IS-A?

The fundamental of IS-A is referring to inheritance, it means when inheritance is apply you can say IS-A applies. e.g.
in the real life world , SUVCar is a Car, the example as follows.

Example of java class

Public class SUVCar extends Car {
   
    run(){}
}
 class Car {
   
   start()  {}
   stop()  {}
}

Here , SUVCar IS-A CAR, because SUVCar inherits by extending the Car class.

What is HAS-A?

The fundamental of HAS-A is referring to composition, it means when association (aggregation or composition) is applies, you can say HAS-A applies. e.g.

Example of java class

 public class Car {
   
   private Engine engine;

    start()  {}

}

class Engine  {
   // for brevity an simplicity I put only 2 methods
   putOil() {}
   String getEngineNo() {}
}

here , we can say Car has-a Engine, because Engine is composed inside the Car class.

Suggestions are welcome in form of comment here .


Connect with

Leave a Reply

Your email address will not be published. Required fields are marked *