What is the difference between method overloading and method overriding in Java?
Overloading is several methods with the same name but different parameters in one class, resolved at compile time. Overriding is a subclass replacing a parent method with the same signature, resolved at runtime.
Explain it simply
At a canteen you can say "one tea" or "one tea with less sugar". Same word, different details, and the counter knows which you mean from what you said: that is overloading. Now imagine the canteen owner's son takes over and makes tea his own way, but you still ask the same way: that is overriding.
Example
class Printer {
void print(int x) { System.out.println("int " + x); }
void print(String s) { System.out.println("String " + s); } // overload
}
class Animal { void speak() { System.out.println("..."); } }
class Dog extends Animal {
@Override
void speak() { System.out.println("Woof"); } // override
}
// new Printer().print(5) prints: int 5
// Animal a = new Dog(); a.speak(); prints: WoofWhat to say in the interview
"Overloading needs a different parameter list; return type alone is not enough. The compiler picks the method from the declared argument types. Overriding needs the same name and parameters, an access level that is not weaker, and a compatible return type. The JVM picks the method from the actual object at runtime. Static, private and final methods cannot be overridden."
Common mistakes
- Changing only the return type and expecting an overload. It will not compile.
- Forgetting
@Override, so a typo in the name silently creates a new method instead.