"What is the difference between overloading and overriding?" is probably the most frequently asked OOP interview question in India, from campus placements to experienced-hire rounds. Both features reuse a method name, which is why students mix them up. But they solve completely different problems and follow completely different rules.
In Polymorphism we saw that overloading gives compile-time polymorphism and overriding gives run-time polymorphism. In this chapter we'll study the exact rules of each, see how the compiler picks an overload, look at the compile errors you get when you break the overriding rules, and finish with the tricky questions where the two meet.
The Core Difference in One Picture
OVERLOADING (same class, same name, DIFFERENT parameters)
class Calculator
add(int, int)
add(int, int, int) ← compiler picks one by looking
add(double, double) at the argument types
OVERRIDING (parent and child, SAME signature, new body)
class Account class SavingsAccount extends Account
interestRate() ─────────▶ interestRate() ← JVM picks one by
returns 0.0 returns 0.035 looking at the objectMethod overloading: defining two or more methods with the same name in the same scope (a class and the members it inherits) but with different parameter lists.
Method overriding: a subclass providing a new implementation of an inherited instance method with the same name and parameter list, so that calls through a parent-type reference run the subclass version.
Overloading is about convenience: one meaningful name for related operations on different inputs. Overriding is about specialisation: a child changes how an inherited operation behaves.
Method Overloading
class Calculator {
int add(int a, int b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; } // different count
double add(double a, double b) { return a + b; } // different types
String add(String a, String b) { return a + b; }
}
public class OverloadDemo {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(2, 3));
System.out.println(c.add(2, 3, 4));
System.out.println(c.add(2.5, 3.5));
System.out.println(c.add("Data", "Base"));
System.out.println(c.add(2, 3.5)); // int widened to double
}
}Output:
5
9
6.0
DataBase
5.5Rules of overloading
The parameter lists must differ in the number, types or order of parameters.
The return type, access modifier and
throwsclause may be anything. They do not distinguish overloads.Parameter names don't count:
add(int a, int b)andadd(int x, int y)are the same method.Static methods, constructors and even
maincan be overloaded. (In Java 17 and 21 the launcher starts the program only frompublic static void main(String[]); Java 25 also accepts an instancemainor amain()without parameters, but an overload such asmain(int)is never an entry point.)
The most common exam question: can you overload on return type alone? No:
class Shape {
int area(int side) { return side * side; }
double area(int side) { return side * side * 1.0; }
}ReturnErr.java:3: error: method area(int) is already defined in class Shape
double area(int side) { return side * side * 1.0; }
^
1 errorWhy? A call like area(5); may ignore the result entirely, so the compiler would have no way to choose. The method signature in Java is the name plus parameter types; the return type is not part of it.
How the Compiler Chooses an Overload
When several overloads could accept the arguments, Java searches in three phases and stops at the first phase that finds a match:
Phase 1: exact match or widening conversions only (e.g.
int→long→double). No boxing, no varargs.Phase 2: also allow boxing/unboxing (
int↔Integer).Phase 3: also allow varargs.
Within a phase, if more than one method fits, the most specific one wins (the one whose parameter types could be passed to the others). If none is most specific, the call is ambiguous.
public class ResolutionDemo {
static void show(long x) { System.out.println("long (widening)"); }
static void show(Integer x) { System.out.println("Integer (boxing)"); }
static void show(int... x) { System.out.println("int... (varargs)"); }
static void only2(Integer x) { System.out.println("Integer (boxing)"); }
static void only2(int... x) { System.out.println("int... (varargs)"); }
static void pick(Object o) { System.out.println("Object"); }
static void pick(String s) { System.out.println("String"); }
public static void main(String[] args) {
int n = 5;
show(n); // all three apply: widening wins
only2(n); // boxing beats varargs
pick(null); // both apply: the more specific String wins
}
}Output:
long (widening)
Integer (boxing)
StringMemory aid: widening > boxing > varargs. Old code relied on widening before boxing and varargs existed (Java 5), and the phases keep that old code behaving the same.
When two overloads are equally specific, you get an ambiguity error. null fits any reference type, and neither String nor StringBuilder is a subtype of the other:
public class NullAmbig {
static void print(String s) { }
static void print(StringBuilder s) { }
public static void main(String[] args) {
print(null);
}
}NullAmbig.java:6: error: reference to print is ambiguous
print(null);
^
both method print(String) in NullAmbig and method print(StringBuilder) in NullAmbig match
1 errorFix it with a cast: print((String) null).
Method Overriding
class Account {
protected double balance = 1000;
Account copy() { // returns Account
Account a = new Account();
a.balance = balance;
return a;
}
double interestRate() { return 0.0; }
static String bankName() { return "Generic Bank"; }
public String toString() { return getClass().getSimpleName() + "[" + balance + "]"; }
}
class SavingsAccount extends Account {
@Override
SavingsAccount copy() { // covariant return type
SavingsAccount s = new SavingsAccount();
s.balance = balance;
return s;
}
@Override
public double interestRate() { return 0.035; } // wider access is allowed
static String bankName() { return "Savings Bank"; } // HIDES, not overrides
}
public class OverrideDemo {
public static void main(String[] args) {
Account acc = new SavingsAccount();
System.out.println(acc.interestRate()); // overridden: run-time choice
System.out.println(acc.copy()); // SavingsAccount's copy()
System.out.println(Account.bankName());
System.out.println(SavingsAccount.bankName());
}
}Output:
0.035
SavingsAccount[1000.0]
Generic Bank
Savings BankRules of overriding (Java)
# | Rule | Why |
|---|---|---|
1 | Same name and same parameter types | Otherwise it's a new (overloaded) method, not a replacement |
2 | Return type: identical for primitives; the same type or a subtype for references (covariant return, Java 5+) | Callers expecting an |
3 | Access cannot be more restrictive (may be wider) | Code that could call the parent's method through a parent reference must still be able to call it |
4 | Cannot throw new or broader checked exceptions (fewer, narrower or unchecked are fine) | Callers only prepared for the parent's exceptions must not be surprised |
5 |
| That's what |
6 |
| They belong to the class, so there's no object to dispatch on |
7 |
| A same-named method in the child is just a new method |
Rules 3 and 4 both protect the same promise: anything you could do with the parent, you can still do with the child. Here's what the compiler says when you break them:
class Account {
public double interestRate() { return 0.0; }
}
class FixedDeposit extends Account {
@Override
double interestRate() { return 0.07; } // public -> package-private
}WeakerErr.java:7: error: interestRate() in FixedDeposit cannot override interestRate() in Account
double interestRate() { return 0.07; } // public -> package-private
^
attempting to assign weaker access privileges; was public
1 errorimport java.io.IOException;
class Reader {
void read() throws IOException { }
}
class FileReaderX extends Reader {
@Override
void read() throws Exception { } // broader checked exception
}ThrowsErr.java:9: error: read() in FileReaderX cannot override read() in Reader
void read() throws Exception { } // broader checked exception
^
overridden method does not throw Exception
1 errorWhy always write @Override
Without @Override, a typo silently creates a brand-new method and your "override" never runs. With it, the compiler catches the mistake:
class Student {
public String toString() { return "Student"; }
}
class Topper extends Student {
@Override
public String tostring() { return "Topper"; } // lowercase s!
}TypoErr.java:6: error: method does not override or implement a method from a supertype
@Override
^
1 errorStatic methods: hiding
In OverrideDemo, bankName() is static in both classes. Which version runs is decided by the type used in the call, at compile time. If you write acc.bankName() through the Account acc reference, you get "Generic Bank" even though the object is a SavingsAccount. That's why calling static methods through an object reference is considered bad style: it looks polymorphic but isn't.
Side-by-Side Comparison
Point | Overloading | Overriding |
|---|---|---|
Purpose | Same operation for different inputs | Change inherited behaviour in a subclass |
Where | Usually the same class (also across parent and child) | Always across parent and child (or interface and class) |
Parameters | Must differ | Must be the same |
Return type | Any; doesn't matter | Same or covariant subtype |
Access modifier | Any | Same or wider |
Checked exceptions | Any | Same, narrower, fewer or none |
static / private / final methods | Can be overloaded | Cannot be overridden |
Binding | Compile time (static binding) | Run time (dynamic binding) |
Polymorphism type | Compile-time | Run-time |
Inheritance needed? | No | Yes |
The Classic Trap: When Overloading Meets Overriding
Here's a question that catches even experienced developers. What does this print?
class A {
void greet(Object o) { System.out.println("A.greet(Object)"); }
}
class B extends A {
void greet(String s) { System.out.println("B.greet(String)"); } // overload, not override!
}
public class TrickDemo {
public static void main(String[] args) {
A ref = new B();
ref.greet("hi"); // compiler only sees A.greet(Object)
B b = new B();
b.greet("hi"); // now both are visible; String is more specific
}
}Output:
A.greet(Object)
B.greet(String)Step by step, for ref.greet("hi"):
Compile time (overload resolution): the reference type is
A.Ahas onlygreet(Object), so the compiler records a call togreet(Object).Run time (dispatch): the JVM looks for an override of
greet(Object)inB. There isn't one, becauseB.greet(String)has a different parameter type, so it's an overload.A's version runs.
The general rule: the compiler picks the signature, the JVM picks the class. Adding @Override to B.greet(String) would have exposed the bug at compile time.
In C++: Name Hiding
C++ has an extra trap. If a derived class declares a function with a name that exists in the base, it hides every base overload with that name, not just the one with the same parameters.
#include <iostream>
class Printer {
public:
virtual void print(int n) { std::cout << "Printer::print(int) " << n << '\n'; }
virtual void print(double d) { std::cout << "Printer::print(double) " << d << '\n'; }
virtual ~Printer() = default;
};
class ColorPrinter : public Printer {
public:
using Printer::print; // remove this line and print(2.5) calls print(int)!
void print(int n) override { std::cout << "ColorPrinter::print(int) " << n << '\n'; }
};
int main() {
ColorPrinter cp;
cp.print(7);
cp.print(2.5);
}Output with the using declaration:
ColorPrinter::print(int) 7
Printer::print(double) 2.5Output after deleting the using line:
ColorPrinter::print(int) 7
ColorPrinter::print(int) 2Without using, name lookup finds print in ColorPrinter and stops; the base's print(double) is never considered, so 2.5 is silently converted to int. Also remember that in C++ only virtual functions can be overridden, and the override specifier plays the role of Java's @Override.
In Python: No Classic Overloading
A Python class has one attribute per name, so a second def with the same name simply replaces the first:
from functools import singledispatchmethod
class Calculator:
def add(self, a, b):
return a + b
def add(self, a, b, c): # silently REPLACES the first add
return a + b + c
c = Calculator()
print(c.add(1, 2, 3))
try:
c.add(1, 2)
except TypeError as e:
print("TypeError:", e)
class Formatter:
@singledispatchmethod
def fmt(self, value):
return f"value: {value}"
@fmt.register
def _(self, value: int):
return f"int: {value:,}"
@fmt.register
def _(self, value: list):
return "list of " + str(len(value))
f = Formatter()
print(f.fmt(1500000))
print(f.fmt([1, 2, 3]))
print(f.fmt(2.5))Output (Python 3.14):
6
TypeError: Calculator.add() missing 1 required positional argument: 'c'
int: 1,500,000
list of 3
value: 2.5Pythonic alternatives are default arguments (def add(self, a, b, c=0)), *args, or functools.singledispatchmethod, which chooses an implementation by the type of the first argument after self, at run time. Overriding, on the other hand, works in Python just as you'd expect: define a method with the same name in the subclass.
Common Mistakes
Trying to overload by return type: compile error.
Changing the parameter type while "overriding" (e.g.
equals(Student s)instead ofequals(Object o)). It becomes an overload, and collections likeHashSetnever call it.@Overridecatches this.Narrowing access in an override (public → protected): compile error.
Thinking static methods can be overridden. They are hidden; the call is decided by the declared type.
Passing
nullto overloaded methods with unrelated reference parameters: ambiguity error.In C++, forgetting
using Base::name;when overriding one overload of a set.
Interview and GATE-Style Questions
Can we overload a method by changing only its return type?
No. The signature used to distinguish methods is the name plus parameter types. Two methods differing only in return type cause "method ... is already defined".
Can we override a static method? A private method?
Neither. A static method with the same signature in the subclass hides the parent's (the declared type chooses it at compile time). Private methods aren't inherited, so a same-named method in the subclass is a new, unrelated method.
Can main() be overloaded? Can it be overridden?
It can be overloaded, but the launcher only uses the standard form, public static void main(String[] args) (Java 25 additionally accepts an instance main or a parameterless main()), as the entry point; other overloads are ordinary methods. The classic static main can't be overridden, only hidden by a subclass's static main.
Given show(long), show(Integer) and show(int...), which runs for show(5)?
show(long). Overload resolution tries widening first, then boxing, then varargs, and stops at the first phase with a match.
What is a covariant return type?
An overriding method may return a subtype of the overridden method's return type, e.g. parent Account copy(), child SavingsAccount copy(). Allowed since Java 5, for reference types only.
Can an overriding method throw a checked exception that the overridden method doesn't?
No, it can't add new or broader checked exceptions. It may throw the same ones, narrower ones (subclasses), fewer, none, or any unchecked exceptions.
class A { void f(Object o) } class B extends A { void f(String s) }. A a = new B(); a.f("x"); Which runs?
A.f(Object). The compiler chooses the signature f(Object) from the reference type A. B.f(String) overloads rather than overrides it, so there is no override to dispatch to at run time.
Summary
Overloading: same name, different parameters, usually in one class; resolved by the compiler. Return type alone can't distinguish overloads.
Overload resolution order: exact/widening → boxing → varargs, then the most specific method; otherwise ambiguous.
Overriding: same signature in a subclass; resolved at run time from the object's class.
Override rules: same parameters, same or covariant return, same or wider access, no new/broader checked exceptions; final, static, private methods and constructors can't be overridden.
Always use
@Override(Java) /override(C++).The compiler picks the signature; the JVM picks the class.
C++ hides base overloads unless you add
using Base::name;. Python has no classic overloading; use default arguments orsingledispatchmethod.
Overriding works best when the parent defines a clear contract for its children to fill in. The next chapter, Abstract Classes vs Interfaces, compares the two Java tools for defining such contracts.