What is the difference between method overloading and method overriding?
Interview preparation resource from Gate Smashers.
Method overloading defines multiple methods with the same name but different parameter lists. The compiler selects the appropriate overload from the method call's arguments, so it is commonly called compile-time polymorphism. Method overriding occurs when a subclass provides its own implementation of an inherited instance method with the same signature; the implementation is selected at runtime based on the actual object, enabling runtime polymorphism.
class Calculator {
// Overloaded methods: same name, different parameter lists
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
class Animal {
String speak() {
return "generic sound";
}
}
class Dog extends Animal {
@Override
String speak() {
return "bark";
}
}
public class Demo {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(1, 2)); // calls add(int, int)
System.out.println(c.add(1.5, 2.5)); // calls add(double, double)
Animal a = new Dog();
System.out.println(a.speak()); // calls Dog.speak() at runtime
}
}Method overloading
Overloading uses the same method name with different parameter lists. The parameter lists must differ by number, types, or order of parameters; changing only the return type does not create a valid overload in Java.
It does not require inheritance, although methods with the same name and different parameter lists may also occur across a class hierarchy. Overload resolution is performed at compile time using the declared types of the arguments.
Method overriding
Overriding occurs when a subclass redefines an inherited instance method with the same name and parameter types. In Java, the overriding method must have the same return type or a covariant return type.
When a method is overridden, a call through a superclass reference is dynamically dispatched to the implementation for the actual object at runtime.
Rules that depend on the language
The following rules are stated for Java. An overriding method cannot reduce the visibility of the inherited method. A final method cannot be overridden. Static methods are hidden rather than overridden, and private methods are not inherited, so they cannot be overridden.
Java also restricts checked exceptions declared by an overriding method: it cannot declare broader checked exceptions than the inherited method. These restrictions do not arise merely from overloading.
When to use each
Use overloading to offer related operations with different input forms, such as accepting two integers, two floating-point values, or three integers. Use overriding when a subtype needs behavior specific to that subtype while preserving the superclass method contract.
