What is method overriding in Python OOP?
a) Redefining a method in a child class that was defined in the parent class
b) Defining multiple methods with the same name in the same class
c) Calling a method from within another method
d) Using a method without parameters
Answer:
a) Redefining a method in a child class that was defined in the parent class
Explanation:
Method overriding in Python OOP occurs when a child class redefines a method that was already defined in its parent class. The overridden method in the child class has the same name and parameters as the method in the parent class but provides a different implementation.
class Parent:
def show_message(self):
print("Message from Parent")
class Child(Parent):
def show_message(self):
print("Message from Child")
# Creating objects of Parent and Child classes
parent = Parent()
child = Child()
parent.show_message() # Output: Message from Parent
child.show_message() # Output: Message from Child
In this example, the Child
class overrides the show_message()
method of the Parent
class, providing its own implementation. When the method is called on an object of the Child
class, the overridden method is executed.
Method overriding allows child classes to customize or extend the behavior of methods inherited from their parent classes, providing more specific functionality.