Curriculum
Method overriding is a feature of object-oriented programming that allows a subclass to provide its own implementation of a method that is already defined in its superclass. This allows the subclass to change the behavior of the method without modifying the superclass’s implementation.
In Python, method overriding is achieved by simply defining a method with the same name as the one in the superclass. When the method is called on an instance of the subclass, the subclass’s implementation of the method will be used.
Here’s an example:
class Shape: def draw(self): print("Drawing a shape") class Rectangle(Shape): def draw(self): print("Drawing a rectangle") shape = Shape() shape.draw() # Output: Drawing a shape rectangle = Rectangle() rectangle.draw() # Output: Drawing a rectangle
In this example, we have a superclass called Shape
with a draw
method that simply prints “Drawing a shape”. We also have a subclass called Rectangle
that inherits from Shape
and overrides the draw
method to print “Drawing a rectangle”.
When we create an instance of Shape
and call the draw
method, the output is “Drawing a shape”. However, when we create an instance of Rectangle
and call the draw
method, the output is “Drawing a rectangle”. This is because the Rectangle
class has overridden the draw
method from the Shape
class.
Method overriding is useful when you want to change the behavior of a method in a subclass without modifying the implementation in the superclass. This allows you to create specialized behavior for a specific class or group of classes without affecting the behavior of other classes.
For example, consider a banking application that has a BankAccount
class with a withdraw
method that allows customers to withdraw money from their account. You might have a subclass called SavingsAccount
that inherits from BankAccount
and overrides the withdraw
method to enforce a limit on the number of withdrawals per month. This allows you to provide specialized behavior for savings accounts without affecting the behavior of other types of bank accounts.