Aggregation

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, cust is 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.name kind 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?

Updated on