Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

What is the benefit of Composition over Inheritance in java?

user-image
Question added by Mohd shahnawaz khan , Associate Project , Cognizant Technology Solution
Date Posted: 2014/01/13
Hatim Laxmidhar
by Hatim Laxmidhar , Self Employed , The Way It Works

This actually a debatable question of Object Oriented Programming design, if one generalise it.

The answer is very subjective as per the requirement.  It is not necessary that Composition over inheritance will always have befits.

It is as simple as it means.

Composition = "has a" relationship

Inheritance = "is a" relationship.

In simple words, if the requirement demands "is a" relationship, inheritance should be used.

If the requirement demands "has a" relationship, composition should be used.

Let me explain this with an example:

We want to store key values in our program.

In order to achieve this,

In Inheritance:

Extend HashMap and call super.put(key, value) and myvalue=super.get(key). 

In Composition:

Create an object of HashMap

HashMap myMap = new HashMap<kyeOjbectType,valueObjectType>();

myMap.put(key,value) and myMap.get(key);

In above example Composition is better approach.

 

Lets take another example of Car that extends MotorVehicle class.

MotorVehicle has members like Engine, Fueltank, Accelerator, Break etc.

Car is a MotorVehicle.

Where as, none of  Engine, Fueltank, Accelerator, or Break is a MotorVehicle. 

MotorVehicle has an Engine. MotorVehicle has a Fueltank. etc.

Here, instead of Car having a MotorVehicle and access Engine, Fueltank etc., it is better to inherit the members.

 

Hope this answers the quesetion.

 

 

 

 

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.