Wednesday, January 21, 2015

What Is IS-A and Hash-A relationship in JAVA?

Before we start to explore this topic in details I hope that you know basic about inheritance in JAVA, If not please go through this link (http://docs.oracle.com/javase/tutorial/java/concepts/inheritance.html) or read some article about inheritance first.
This is some of the common question asked in interview and also useful for the design class that follow good OO practice.

IS-A

The concept of the IS-A relationship is based on the Inheritance or Interface implementation. You can define IS-A Relationship as “This thing is type of that thing”. 

For Example:- Car is a type of Vehicles. In OO we can say that “Car IS-A Vehicle
You can express IS-A relationship in Java with keyword “extends” for Inheritance and “implements” for Interface.

For Example:-

public class Vehicle
{
       //Class Code goes here
}

public class Car extends Vehicle
{
       //Car class code goes here
       //This class also inherits Vehicle class Methods and Variables

}


So from above code you can say that Car has IS-A relationship with Vehicle. 
This inheritance tree might be go down also like

public class Vehicle { ... }
public class Car extends Vehicle { ... }
public class Toyota extends Car { ... }

From above code you can say following statements

“Car extends Vehicle” means “Car IS-A Vehicle.”
“Toyota extends Car” means “Toyota IS-A Car.”

You can also say that “Toyota IS-A Vehicle.” Because class Toyota is Instance Of class Vehicle ( Toyota instanceof Vehicle is true )

Below Image illustrate the inheritance tree for Vehicle,Car and Toyota. Arrow moves from subclass to superclass.





HAS-A
HAS-A is not based on inheritance, but it is based on the uses and access of one class to other class’s methods and variables. 

We can say class Car HAS-A Engine if class Car hash an instance of class Engine.
For this code look like this

public class Vehicle { }
public class Car
{
       public Engine engine;
}
public class Engine { }

From above code, Car hash an instance variable of class Engine, so we can say that  “Car HAS-A Engine”. Car has a reference to the class Engine, using this reference Car class invoke methods in class Engine or access variable in class Engine.

It good to use HAS-A for good OO design.

There are some point when too used IS-A or HAS-A relationship in code or project.
  • Don't use IS-A (Inheritance or Interface) just to get code reuse If all you really want is to reuse code and there is no IS-A relationship in sight, use HAS-A relationship.         
  • Don't use Inheritance just to get at polymorphism If all you really want is polymorphism, but there is no natural IS-A relationship, use HAS-A with interfaces implementation. 


No comments:

Post a Comment