Which is the Best Java Web Framework ?

Java - Interview Questions and Answers on Composition

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. 

Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
comments powered by Disqus


Try our new Java Interview Questions Search Tool.

There are more than 1000 questions with practice tests.

It's updated daily and It's Awesome.


Try our new Java Practice Test tool.

There are more than 200 questions and expanding quickly. It's updated daily and It's Awesome.