What is the difference between method overriding and method overloading in object-oriented programming?
sobes.tech AI
Answer from AI
Method overriding is when a subclass provides its own implementation of a method that is already defined in the base class. This allows changing the behavior of the method for subclass objects.
Method overloading is the creation of multiple methods with the same name but different parameters (types or number). In some languages (e.g., Java, C++), this is supported at the language level, while in Python, overloading is implemented differently, for example, through default parameters or type checks within the method.
Example of overriding:
class Animal:
def sound(self):
print("Some sound")
class Dog(Animal):
def sound(self):
print("Bark")
Overloading in Python is usually simulated as follows:
def add(a, b, c=None):
if c is not None:
return a + b + c
return a + b
Thus, overriding changes the behavior of an inherited method, while overloading allows a method name to work with different sets of parameters.