Inheritance and polymorphism are two fundamental concepts in object-oriented programming (OOP). They allow developers to create more efficient, reusable, and scalable code.
What is Inheritance?
Inheritance is a mechanism in OOP that allows a class to inherit properties and methods from another class. The class that is being inherited from is called the "base class" or "superclass," and the class that inherits from it is called the "derived class" or "subclass."
Example
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Woof!"
dog = Dog("Buddy")
print(dog.speak()) # Output: Woof!
In the example above, the Dog
class inherits from the Animal
class. The Dog
class has its own implementation of the speak
method, which overrides the one in the Animal
class.
What is Polymorphism?
Polymorphism is the ability of an object to take on many forms. In the context of OOP, it refers to the ability of a subclass to use a method or property that is defined in its superclass.
Example
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
def animal_speak(animal):
print(animal.speak())
dog = Dog("Buddy")
cat = Cat("Kitty")
animal_speak(dog) # Output: Woof!
animal_speak(cat) # Output: Meow!
In the example above, the animal_speak
function takes an Animal
object as an argument and calls its speak
method. The actual method that gets called is determined at runtime based on the type of the object.
Conclusion
Inheritance and polymorphism are powerful tools in OOP that allow developers to create more flexible and maintainable code. By understanding these concepts, you can become a more effective programmer.
For more information on OOP, check out our Object-Oriented Programming Tutorial.