Composition VS Inheritance
Composition
Java composition is achieved by using instance variables that refers to other objects.
Inheritance
- In Java, when an “Is-A” relationship exists between two classes we use Inheritance
- The parent class is termed super class and the inherited class is the sub class
- The keyword “extend” is used by the sub class to inherit the features of super class
- Inheritance is important since it leads to reusability of code
Example
class subClass extends superClass
{
//methods and fields
}
The difference between Composition and Inheritance
The difference between Composition and Inheritance is that with Composition you can reuse code without extending it with Inheritance you must extend the code to reuse classes.
Composition you can use many classes