Difference between inheritance and composition

Inheritance and Composition are providing the reusability concept. If you are a beginner then you should read about the inheritance in Java and Composition in java in detail. After that can relate the inheritance and composition. This article helps you to find the difference between inheritance and composition and after that, you can use them according to your scenarios.
There are many differences between Composition and Inheritance in Java.

Difference between inheritance and composition

Re-usability restriction

Inheritance: In Inheritance, you can only extend only one class. You can’t extend more than one class. It means you can reuse the code of only one class.
Composition: By the use of Composition we can use functionalities from multiple classes. In Java, multiple inheritances don’t support so in that you must use Composition.

Static vs Dynamic

Inheritance:  In Inheritance, if we want to use the functionality of any class then We have to define which class we are extending in code. We can’t change it at runtime.
Composition: By the use of Composition we just need to define a type that you want to use. It can hold its different implementation. The composition provides more flexibility than Inheritance.

Unit testing

Inheritance: If your application is designed by use of inheritance and you want to test the functionality of child class. Then you need to test the parent class with child classes. There is no way you can provide the mock implementation of the parent class.
Composition: If your application is designed by the use of Composition then it is easier to test because you can supply the mock implementation of the classes.

Final classes

Inheritance: Suppose your application has some final classes and you want to use the functionality of those classes. But you can’t use them through the inheritance. Because as per the Java rule final class can’t be inherited.
Composition: By use of composition you can use the functionality from final classes.

difference between inheritance and composition

Leave a Comment