Explain method overloading and overriding in Java
Quick Summary: Method overloading defines multiple methods with the same name but different parameter lists within a class resolved at compile time; method overriding redefines an inherited instance method in a subclass with a compatible signature resolved at runtime.
Direct Interview Answer
Method Overloading (compile-time / static polymorphism) lets one class expose multiple methods sharing a name as long as their parameter count, types, or order differ. Return type alone cannot distinguish overloaded methods.
Method Overriding (runtime / dynamic polymorphism) lets a subclass provide a specialized implementation of a non-private, non-static, non-final superclass method with the same parameter signature and same or narrower covariant return type.
Detailed Technical Explanation
During method resolution, the Java compiler picks the target overloaded signature using reference types known at compile time. At runtime, however, the JVM consults the actual object’s virtual method table (vtable) to dispatch the overridden method on the concrete subclass instance.
Remember: static methods cannot be overridden; defining a static method with the same signature in a subclass only hides the parent static method.
Practical Walkthrough
Observe how compile-time overloading chooses between scalar and batch arguments while runtime overriding executes subclass pricing logic through a parent reference.
class PaymentProcessor {
void pay(int inrAmount) {
System.out.println("Base INR charge: " + inrAmount);
}
void pay(int inrAmount, String promoCode) { // Overloading
System.out.println("Base INR charge: " + inrAmount + " promo=" + promoCode);
}
}
class UpiProcessor extends PaymentProcessor {
@Override
void pay(int inrAmount) { // Overriding
System.out.println("UPI instant zero-fee debit: " + inrAmount);
}
}
public class PolymorphismDemo {
public static void main(String[] args) {
PaymentProcessor ref = new UpiProcessor();
ref.pay(4500);
ref.pay(4500, "EARLY10");
}
}
UPI instant zero-fee debit: 4500 Base INR charge: 4500 promo=EARLY10
Real-World Production Use Case
Strategy Pattern implementations in billing engines (CardProcessor, UpiProcessor implementing a common PaymentGateway interface) paired with overloaded convenience helpers for callers.
Common Interview Mistakes to Avoid
- Omitting the @Override annotation — typos silently turn an intended override into an unrelated new method.
- Trying to reduce visibility (e.g., making an overridden public method protected), which fails compilation.
- Expecting static methods to dispatch polymorphically like instance overrides.