IS a vs HAS a in Java
- IS-A Relationship in Java
- HAS-A Relationship in Java
- Key Differences Between IS-A Relationship and HAS-A Relationship
One of the key features of using an object-oriented programming language is that we can reuse a code multiple times. Generally, we can use two concepts, Inheritance and Composition, to achieve reusability.
Inheritance is an IS-A relationship, and Composition is a HAS-A relationship. Both the concepts differ in a certain way but have the same goal, reusability.
Let us see the difference between these two concepts below.
IS-A Relationship in Java
An Inheritance or the IS-A relationship in Java refers to the relationship of two or more classes. Inheritance can be achieved by utilizing the extends
keyword in Java. We can inherit a parent class to use its methods and variables in a child class.
In the sample code below, we have two classes, Animal
and Dog
, the Animal
class has a function whatAmI()
that returns a String, while the Dog
class extends the class Animal
which is a concept of Inheritance.
This Dog
is an Animal
relationship. The Dog
class can now access the whatAmI()
method from its parent class.
class Animal {
public String whatAmI() {
return "I belong to Animal class";
}
}
class Dog extends Animal {
public void aboutMe() {
System.out.println("I am a Dog class and " + whatAmI());
}
}
Output:
I am a Dog class and I belong to Animal class
HAS-A Relationship in Java
Unlike Inheritance, the Composition or the HAS-A relationship does not use any keyword like extends
. We create an object of the parent class or whichever class we want to use in this method.
In the following example, again, we have two classes, Legs
and Dog
.
Legs
has a method howManyLegs()
. In the Dog
class, we create an object of the Legs
class and use that object to call the howManyLegs()
function.
Now, here we can see that the Composition concept is being applied, Dog
HAS-A Legs
or Dog
class HAS-A property of Legs
.
class Legs {
public String howManyLegs() {
return "I have four legs";
}
}
class Dog {
Legs legs = new Legs();
public void aboutMe() {
System.out.println("I am a Dog class and " + legs.howManyLegs());
}
}
Output:
I am a Dog class and I have four legs
Key Differences Between IS-A Relationship and HAS-A Relationship
IS-A | HAS-A |
---|---|
It is a concept of Inheritance | It is a concept of Composition |
A class cannot extend more than one class. | A class can have HAS-A relationship with multiple other classes |
A final class cannot be extended in Inheritance | We can reuse final classes in Composition |
Inheritance is static binding and cannot be changed at runtime | Composition is dynamic binding and is flexible for changes |
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
LinkedIn