Are Composition and Inheritance the same? If I want to implement the composition pattern, how can I do that in Java?
They are absolutely different. Inheritance is an "is-a" relationship. Composition is a "has-a".
You do composition by having an instance of another class C
as a field of your class, instead of extending C
. A good example where composition would've been a lot better than inheritance is java.util.Stack
, which currently extends java.util.Vector
. This is now considered a blunder. A stack "is-NOT-a" vector; you should not be allowed to insert and remove elements arbitrarily. It should've been composition instead.
Unfortunately it's too late to rectify this design mistake, since changing the inheritance hierarchy now would break compatibility with existing code. Had Stack
used composition instead of inheritance, it can always be modified to use another data structure without violating the API.
I highly recommend Josh Bloch's book Effective Java 2nd Edition
- Item 16: Favor composition over inheritance
- Item 17: Design and document for inheritance or else prohibit it
Good object-oriented design is not about liberally extending existing classes. Your first instinct should be to compose instead.
See also:
as another example, consider a car class, this would be a good use of composition, a car would "have" an engine, a transmission, tires, seats, etc. It would not extend any of those classes.
Composition means HAS A
Inheritance means IS A
Example
: Car has a Engine and Car is a Automobile
In programming this is represented as:
class Engine {} // The engine class.
class Automobile{} // Automobile class which is parent to Car class.
// Car is an Automobile, so Car class extends Automobile class.
class Car extends Automobile{
// Car has a Engine so, Car class has an instance of Engine class as its member.
private Engine engine;
}
Composition is just as it sounds - you create an object by plugging in parts. This is accomplished with Interfaces. For example, using the Car example above,
Car implements iDrivable, iUsesFuel, iProtectsOccupants
Motorbike implements iDrivable, iUsesFuel, iShortcutThroughTraffic
House implements iProtectsOccupants
Generator implements iUsesFuel
So with a few standard theoretical components you can build up your object. It's then your job to fill in how a House protects it's occupants, and how a Car protects it's occupants.
Inheritance is like the other way around. You start off with a complete (or semi-complete) object and you replace or Override the various bits you want to change.
For example, MotorVehicle may come with a Fuelable method and Drive method. You may leave the Fuel method as it is because it's the same to fill up a motorbike and a car, but you may override the Drive method because the Motorbike drives very differently to a Car.
With inheritance, some classes are completely implemented already, and others have methods that you are forced to override. With Composition nothing's given to you. (but you can Implement the interfaces by calling methods in other classes if you happen to have something laying around).
Compisition is seen as more flexible, because if you have a method such as iUsesFuel, you can have a method somewhere else (another class, another project) that just worries about dealing with objects that can be fueled, regardless of whether it's a car, boat, stove, barbecue, etc. Interfaces mandate that classes that say they implement that interface actually have the methods that that interface is all about. For example,
iFuelable Interface:
void AddSomeFuel()
void UseSomeFuel()
int percentageFull()
then you can have a method somewhere else
private void FillHerUp(iFuelable : objectToFill) {
Do while (percentageFull <= 100) {
objectToFill.AddSomeFuel;
}
Strange example, but it's shows that this method doesn't care what it's filling up, because the object implements iUsesFuel, it can be filled. End of story.
If you used Inheritance instead, you would need different FillHerUp methods to deal with MotorVehicles and Barbecues, unless you had some rather weird "ObjectThatUsesFuel" base object from which to inherit.
The answer given by @Michael Rodrigues is not correct (I apologize; I'm not able to comment directly), and could lead to some confusion. Interface implementation is a form of inheritance... when you implement an interface, you're not only inheriting all the constants, you are committing your object to be of the type specified by the interface; it's still an "is-a" relationship. If a car implements Fillable, the car "is-a" Fillable, and can be used in your code wherever you would use a Fillable.
Composition is fundamentally different from inheritance. When you use composition, you are (as the other answers note) making a "has-a" relationship between two objects, as opposed to the "is-a" relationship that you make when you use inheritance. So, from the car examples in the other questions, if I wanted to say that a car "has-a" gas tank, I would use composition, as follows:
public class Car {
private GasTank myCarsGasTank;
}
Hopefully that clears up any misunderstanding.
Inheritance brings out IS-A relation. Composition brings out HAS-A relation.
Statergy pattern explains that Composition should be used in cases where there are families of algorithms defining a particular behaviour.
Classic example being of a duck class which implements a fly behaviour.
public interface Flyable{
public void fly();
}
public class Duck {
Flyable fly;
public Duck(){
fly=new BackwardFlying();
}
}
Thus we can have multiple classes which implement flying eg:
public class BackwardFlying implements Flyable{
public void fly(){
Systemout.println("Flies backward ");
}
}
public class FastFlying implements Flyable{
public void fly(){
Systemout.println("Flies 100 miles/sec");
}
}
Had it been for inheritance we would have two different classes of birds which implement the fly function over and over again.thus inheritance and composition are completely different.