Composition in OOP
Suppose a BankAccount must have a Customer.
That Customer is created inside the BankAccount — not shared with anyone else.
If the account is deleted, the customer details are also gone.
That’s Composition.
Composition means:
-
One class owns the other class object
-
The lifecycle of the owned class depends on the owner
-
Strong bonding → like “part-of” relationship
In simple English:
-
Aggregation → "Has-a" (loose)
-
Composition → "Part-of" (tight)
Simple Code:
class Customer:
def __init__(self, name, cnic):
self.name = name
self.cnic = cnic
class BankAccount:
def __init__(self, name, cnic, balance):
self.customer = Customer(name, cnic) # Composition: created inside
self.balance = balance
def show_details(self):
print(f"{self.customer.name} has balance {self.balance}")
How to Use:
acc = BankAccount("Maham", "12345-6789012-3", 5000)
acc.show_details()
Output:
Maham has balance 5000
Key Points:
-
Customerobject is part ofBankAccount -
If
BankAccountis deleted →Customeris deleted too -
Customer is not shared with any other account
-
It’s a tight relationship
Analogy:
-
BankAccount can’t exist meaningfully without its Customer
-
Customer created inside BankAccount → composition