Composition in OOP

Please explain about composition in OOP. in order to build it, Do you use interface or inheritance?

Composition is a “has a” relationship.

see here

OO composition is about creating object clases that act as re-usable code building blocks for more complex class objects. So a Computer for example is composed of a CPU, RAM, a fan, a storage device, circuit boards (e.g. motherboard), an optical device (e.g. DVD drive), a wireless network device etc.

By creating object classes for each of the above components, when you write your Computer object class its data types are made up of all the other object classes you’ve already made (i.e. it composes those object class data types).

If you go on to write a Smart Phone object class, that would be composed of a CPU, RAM, a storage device, a wireless network device. You can then just re-use the same object classes in your Smart Phone class as those objects that are also being used in the Computer.

Thanks technowonder!

Can someone express programmatically the difference between Composition and Aggregation? I know that Composition hints that if the parent object is destroyed then so are the contained objects, but how does that differentiate programmatically from aggregation where the aggregated objects are not destroyed?

The difference is subtle and is more conceptual than anything.

Let’s say you needed to write a Car class, the needs of the end user come into play.

If your user is a new car dealership, then destroying the car should destroy all the components, as far as your system is concerned. When instantiating this Car, the constructor would create instances of all the components and prompt the user for details.

However, if the user is a car salvage yard, then all the components have a ‘life’ beyond the life of the car and should be retained after the car is destroyed. In this case the constructor would create only the car ‘container’ and the program would prompt for, and add, all the components that go into that particular car.