Difference between Inheritance and Composition in Java
In this tutorial, you are going to learn about the difference between Inheritance and Composition and also how to use it in Java Programming language. Although both of the features are used for the reusability of code there are some differences you must know.
Inheritance vs Composition
- The major difference is of “is-a” and “has-a”
For-example – Rose is a flower. (This is inheritance)
Mobile has a battery. (This is composition) - In Inheritance, child class is dependent on a parent class whereas, in Composition, both child and parent class are independent.
- A final class cannot be extended in Inheritance whereas, it can by the use of Composition.
- The composition is much better than Inheritance in the case of Java.
Example Code for differentiation in Java
Let’s consider an example of “Rose is a flower” for inheritance:
package rose; class Flower { String name; Flower() { name = "N/A"; } public void name1(String n) { name = n; System.out.println(name+ " is a flower"); } } class Rose extends Flower { public void name2(String n) { name1(n); } public static void main(String[] args) { Rose r = new Rose(); r.name2("Rose"); } }
Output:-
Rose is a flower
Now let’s consider an example of “Mobile has a battery” for composition:
package composition; class mobile { String part; public void part(String name) { part = name; System.out.println("Mobile has a "+part); } } class Part { public String getPartName() { return "Battery"; } } public class Composition { public static void main(String[] args) { mobile m = new mobile(); Part p = new Part(); m.part(p.getPartName()); } }
Output:-
Mobile has a Battery
Conclusion
The composition is a much better feature than Inheritance in Object-Oriented Language like Java. The simple difference we have to remember at the end between inheritance and composition is of which is an “is-a” relationship and which is a “has-a” relationship.
Also, read: How to make an image blur in java
Leave a Reply