OOP Advanced

Inheritance, Polymorphism, Encapsulation aur aur bhi concepts

1. Inheritance

Inheritance me ek class (Child) dusri class (Parent) ke attributes aur methods inherit karti hai. Ye reusability ke liye use hota hai.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print(self.name, "makes a sound")

class Dog(Animal):
    def speak(self):
        print(self.name, "barks")

dog = Dog("Tommy")
dog.speak()

Output:

Tommy barks

2. super() Keyword

super() ka use parent class ke constructor/method call karne ke liye hota hai.

class Vehicle:
    def __init__(self, brand):
        self.brand = brand

class Car(Vehicle):
    def __init__(self, brand, model):
        super().__init__(brand)
        self.model = model

c = Car("Toyota", "Corolla")
print(c.brand, c.model)

Output:

Toyota Corolla

3. Polymorphism

Polymorphism ka matlab hai alag-alag classes me same method ka different behavior.

class Cat(Animal):
    def speak(self):
        print(self.name, "meows")

animals = [Dog("Tommy"), Cat("Kitty")]

for a in animals:
    a.speak()

Output:

Tommy barks
Kitty meows

4. Encapsulation

Encapsulation ka matlab hai internal details ko hide karna aur sirf methods ke through access dena.

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance   # private variable

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance

account = BankAccount(1000)
account.deposit(500)
print(account.get_balance())

Output:

1500

Summary