Difference between Inheritance and Composition in Java
When we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. In doing this, we can reuse the fields and methods of the existing class without having to write them ourself.
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
Types of Inheritance are:
- Single inheritance
- Multi-level inheritance
- Multiple inheritances
- Hybrid inheritance
- Hierarchical inheritance
Example of Inheritance:
addition of a+b is:11
Here, class B is the derived class which inherit the property(add method) of the base class A.
The composition also provides code reusability but the difference here is we do not extend the class for this.
Example of Composition:
Let us take an example of the Library.
Title : EffectiveJ Java and Author : Joshua Bloch Title : Thinking in Java and Author : Bruce Eckel Title : Java: The Complete Reference and Author : Herbert Schildt
Difference between Inheritance and Composition:
|1.||In inheritance, we define the class which we are inheriting(super class) and most importantly it cannot be changed at runtime||Whereas in composition we only define a type which we want to use and which can hold its different implementation also it can change at runtime. Hence, Composition is much more flexible than Inheritance.|
|2.||Here we can only extend one class, in other words more than one class can’t be extended as java do not support multiple inheritance. ||Whereas composition allows to use functionality from different class.|
|3.||In inheritance we need parent class in order to test child class.||Composition allows to test the implementation of the classes we are using independent of parent or child class.|
|4.||Inheritance cannot extend final class.||Whereas composition allows code reuse even from final classes.|
|5.||It is an is-a relationship.||While it is a has-a relationship.|
Please Login to comment...