Junior — Middle
How to distinguish method overloading from method overriding in object-oriented programming?
sobes.tech AI
Answer from AI
Method overloading and method overriding are different concepts in OOP:
-
Method overloading is having multiple methods in the same class with the same name but different parameters (type, number). This allows calling the method with different arguments.
-
Method overriding is when a subclass provides its own implementation of a method that is already defined in the base class with the same signature (name and parameters). This allows changing the behavior of the method for the subclass.
Example in Java:
class Animal {
void sound() {
System.out.println("Some sound");
}
void sound(String mood) { // overloading
System.out.println("Sound when " + mood);
}
}
class Dog extends Animal {
@Override
void sound() { // overriding
System.out.println("Bark");
}
}
Here, sound() in the Dog class overrides the method from the base class, and sound(String mood) is an overload of the method in the same Animal class.