Superclass and Subclass:
- Definition: Inheritance allows a class (subclass) to inherit attributes and methods from another class (superclass). python
class Animal: def __init__(self, name): self.name = name def speak(self): pass class Dog(Animal): def speak(self): return f"{self.name} says Woof!"- Explanation: The
Dogclass inherits from theAnimalclass. Thespeakmethod is overridden in theDogclass.
- Explanation: The
Method Overriding:
- Definition: Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. python
class Cat(Animal): def speak(self): return f"{self.name} says Meow!"- Explanation: The
Catclass overrides thespeakmethod of theAnimalclass to provide its own implementation.
- Explanation: The