Overloading vs Overriding
TL;DR
- Overloading (Compile-Time Polymorphism): Multiple methods in the same class with the exact same name, but different parameters.
- Overriding (Run-Time Polymorphism): A method in a child class that replaces a method in the parent class with the exact same name and the exact same parameters.
Concept
Method Overloading is a convenience feature. If you write a Math class, you don’t want to name your methods addInts(int a, int b) and addDoubles(double a, double b). You want to just name them both add(). The Java compiler looks at the arguments you pass in, and figures out exactly which method to call at compile time.
Method Overriding is the heart of Object-Oriented polymorphism. An Animal class has a makeSound() method. A Dog class inherits from Animal, but wants to bark. So, the Dog class overrides the makeSound() method. When the program runs, the JVM looks at the actual object in memory (is it a generic Animal or a Dog?) and executes the correct method.
Examples
class MathUtils {
// OVERLOADING
// Same name, different parameters. Solved at Compile-Time.
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
}
class Animal {
public void makeSound() {
System.out.println("Generic animal sound");
}
}
class Dog extends Animal {
// OVERRIDING
// Exact same signature as the parent. Replaces parent behavior at Run-Time.
@Override
public void makeSound() {
System.out.println("Woof");
}
}
public class Demo {
public static void main(String[] args) {
Animal myAnimal = new Dog();
// At compile time, the variable is of type 'Animal'.
// At run time, Java sees it is actually a 'Dog' and prints "Woof".
myAnimal.makeSound();
}
}
Interview Questions
Q: Can you Overload a method by only changing its Return Type?
A: No. Overloading requires a change in the parameter list (number of parameters, or type of parameters).
If you have public int add(int a, int b) and public double add(int a, int b), the Java compiler will throw an error. If a user calls add(5, 5), the compiler has no way to know which method you intended to call.
Q: Can you Override a static method?
A: No. Static methods belong to the Class, not the Object instance. Overriding relies on Run-Time Polymorphism (Dynamic Method Dispatch) to check the type of the object instance in memory. Because static methods don’t use object instances, they cannot be overridden. If a child class creates a static method with the same signature as a parent’s static method, this is called Method Hiding, not overriding.