Q1. Difference between Compositions and Inheritance ?
Ans. Inheritance means a object inheriting reusable properties of the base class. Compositions means that an abject holds other objects.
In Inheritance there is only one object in memory ( derived object ) whereas in Composition , parent object holds references of all composed objects.
From Design perspective - Inheritance is "is a" relationship among objects whereas Composition is "has a" relationship among objects.
Q2. Can we compose the Parent Class object like this ?
class BuggyBread1 extends BuggyBread2 {
private BuggyBread2 buggybread2;
public static void main(String[] args){
buggybread2 = new BuggyBread2();
}
}
Ans. Yes.
Q3. What are the difference between composition and inheritance in Java?
Ans. Composition - has-a relationship between classes.
Inheritance - is-a relationship between classes.
Composition - Composing object holds a reference to composing classes and hence relationship is loosely bound.
Inheritance - Derived object carries the base class definition in itself and hence its tightly bound.
Composition - Used in Dependency Injection
Inheritance - Used in Runtime Polymorphism
Composition - Single class objects can be composed within multiple classes.
Inheritance - Single class can only inherit 1 Class.
Composition - Its the relationship between objects.
Inheritance - Its the relationship between classes.