IKH

Composition vs Aggregation

Composition

Without existing container object if there is no chance of existing contained object then the container and contained objects are strongly associated and that strong association is nothing but composition.

Example

Python
University contains several departments and without existing university object there is no 
chance of existing department object. Hence university and department objects are strongly 
associated and this strong association is nothing but composition.

Output

PowerShell
5

Aggregation

Without existing container object if there is a chance of existing contained object then the
container and contained objects are weakly associated and that weak association is nothing but Aggregation.

Example

Python
Department contains several Professors. Without existing Department still there may be a 
chance of existing Professor. Hence Department and Professor objects are weakly associated,
which is nothing but Aggregation.

Output

PowerShell
6

Example

Python
class Student: 
collegeName='DURGASOFT' 
def __init__(self,name): 
self.name=name 
print(Student.collegeName) 
s=Student('Durga') 
print(s.name)

Output

PowerShell
DURGASOFT
Durga
In the above example without existing Student object there is no chance of existing his name. 
Hence Student Object and his name are strongly associated which is nothing but Composition.
But without existing Student object there may be a chance of existing collegeName. Hence 
Student object and collegeName are weakly associated which is nothing but Aggregation.

Conclusion

  • The relation between object and its instance variables is always Composition where as the relation between object and static variables is Aggregation.

Note

  • Whenever we are creating child class object then child class constructor will be executed. If the child class does not contain constructor then parent class constructor will be executed, but parent object won’t be created.

Example

Python
class P: 
def __init__(self): 
print(id(self)) 
class C(P): 
pass 
c=C() 
print(id(c))

Output

PowerShell
6207088
6207088

Example

Python
class Person: 
def __init__(self,name,age): 
self.name=name 
self.age=age 
class Student(Person): 
def __init__(self,name,age,rollno,marks): 
super().__init__(name,age) 
self.rollno=rollno 
self.marks=marks 
def __str__(self): 
return 'Name={}\nAge={}\nRollno={}\nMarks={}'.format(self.name,self.age,self.rollno
,self.marks) 
s1=Student('durga',48,101,90) 
print(s1)

Output

PowerShell
Name=durga
Age=48
Rollno=101
Marks=90

Note

  • In the above example whenever we are creating child class object both parent and child class constructors got executed to perform initialization of child object.

Report an error