Composition
"Have a " Relationship OR "Must have" relationship between two or more classes.
Container class contains component's class object
For example a Car is composed of engine and body. Where Car is a container class and both Engine and Body are components class.
Life Time Issue in Composition
- Life time of component objects depends on container class
- If Container object destroyed, component objects will be also destroyed
Car Example
- There is a composition relationship between car's body and engine.
- Car must have Engine and body
- If Car destroyed, both Engine and Body will be destroyed
|
Output
Engine created
Body created
Car created
Engine Start
Saloon Type
Same problem with Data Members
Example : Create car(price) class as container object with engine(hp) and body(size) as component objects
|
Output:
Engine Power 800
Saloon Size 5
Car Price 40000
Example : Create 4 cup of tea and serve into tray.
CupofTea consist of milk, sugar, Teabag and water.
Container Class :
CupofTea
Component Class :
Milk (qty)
sugar(spoone)
Teabag(make)
Water(qty)
Tray :
Array of cupoftea
|
Output:
Cup no = 0
Milk=5
sugar=1
Teabag=Lipton
water=3
...........................
Cup no = 1
Milk=5
sugar=10
Teabag=Lipton
water=3
...........................
Cup no = 2
Milk=5
sugar=0
Teabag=Olpers
water=3
...........................
Cup no = 3
Milk=5
sugar=15
Teabag=TarakChai
water=3
...........................
Hmmm, Nice Codes. Surely Will Help Other As It Did To Me. Keep Sharing Something Like This...
ReplyDeleteAoA
ReplyDeletei see yur site its so informatic site , i appriciate yur working
thanx for sharing yur efforts