Letโs talk about Aggregation in Object-Oriented Programming โ but in our simple, Desi style ๐
โจ What is Aggregation?
-
Itโs a type of โhas-aโ relationship.
-
Means: One class contains another class, but both can live independently.
-
Like: A University has Students, but Students can exist without a University too.
๐ฆ Real-life Bank Example:
class Customer:
def __init__(self, name):
self.name = name
class BankAccount:
def __init__(self, customer, balance):
self.customer = customer # Aggregation
self.balance = balance
def show_account(self):
print(f"Account of {self.customer.name}, Balance: {self.balance}")
Usage:
cust = Customer("Maham")
account = BankAccount(cust, 5000)
account.show_account()
-
Here, BankAccount has a Customer.
-
But even if you delete
account,custis still there. So both are not tightly dependent.
๐ Aggregation vs Composition:
Concept | Aggregation | Composition |
|---|---|---|
Dependency | Weak (can exist independently) | Strong (cannot exist separately) |
Example | BankAccount has a Customer | Car has an Engine (engine dies with car) |
๐ Common Questions:
-
Q: Is aggregation same as inheritance?
โ No yaar, inheritance is "is-a", aggregation is "has-a". -
Q: Can we access aggregated class properties?
โ Haan ji!self.customer.namekind of access is common. -
Q: What happens if parent is deleted?
โ Nothing happens to the child in aggregation. It survives.
okay simply a class can be a property in another class right?
Exactly! ๐ก
-
Yes, a class can be used as a property inside another class
-
Thatโs called a "has-a" relationship (like aggregation or composition)
Example:
class Engine:
def __init__(self, horsepower):
self.horsepower = horsepower
class Car:
def __init__(self, engine):
self.engine = engine # Engine is used as a property
def show(self):
print(f"Car with {self.engine.horsepower} HP engine")
Output:
e = Engine(120)
c = Car(e)
c.show()
โ๏ธ So yes โ class as a property = totally valid and very useful!
Want the composition example next?