The code below demonstrates the concept of inheritance in object-oriented programming. Let's go through it step by step:
class Animal:
def speak(self):
print("The animal makes a sound.")
class Dog(Animal):
def speak(self):
print("The dog barks.")
class Cat(Animal):
def speak(self):
print("The cat meows.")
dog = Dog()
cat = Cat()
dog.speak()
cat.speak()
The Animal class is defined with a method called speak(). This method simply prints the message "The animal makes a sound."
The Dog class is created as a subclass of Animal by including (Animal) after the class name in the class definition. This means that Dog inherits all the properties and methods of the Animal class.
Inside the Dog class, the speak() method is overridden by defining a new implementation specific to dogs. In this case, the method prints the message "The Dog Barks."
Similarly, the Cat class is created as a subclass of Animal and overrides the speak() method to print "The cat meows."
Instances of the Dog and Cat classes are created using the Dog() and Cat() constructors, respectively. These instances, dog and cat, are objects representing a dog and a cat.
The speak() method is called on the cat and dog objects using the dot notation (e.g., cat.speak() and dog.speak()). This invokes the speak() method specific to each class.
When the speak() method is called on the cat object, it executes the code defined in the Cat class, printing "The cat meows." Similarly, when called on the dog object, it executes the code defined in the Dog class, printing "The Dog Barks."
Top comments (0)