What is IS-A and HAS-A relationship in JAVA?

IS-A Relationship:

IS-A relationship is java represents Inheritance. It indicates that, "Class A is of Class B type". 
ex: Banana is a fruit, Car is a vehicle.
Inheritance is unidirectional as banana is a fruit , but all fruits are not bananas. 
        It is a key point to note that you can easily identify the IS-A relationship. Wherever you see an extends keyword or implements keyword in a class declaration, then this class is said to have IS-A relationship.

HAS-A Relationship:

Has-A means an instance of one class “has a” reference to an instance of another class or another instance of same class.There is no specific keyword to implement HAS-A relationship but mostly we are depended upon “new” keyword.
HAS-A relationship is  also called as "Composition". Composition(HAS-A) simply mean the use of instance variables that are references to other objects. For example Maruti has Engine, or House has Bathroom.

Summary:

  • IS-A relationship based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance.
  • Has-a relationship is composition relationship which is a productive way of code reuse.

No comments:

Post a Comment