Chapter 10 of 26

Method Overloading vs Method Overriding

"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 object

Method 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.5

Rules of overloading

  • The parameter lists must differ in the number, types or order of parameters.

  • The return type, access modifier and throws clause may be anything. They do not distinguish overloads.

  • Parameter names don't count: add(int a, int b) and add(int x, int y) are the same method.

  • Static methods, constructors and even main can be overloaded. (In Java 17 and 21 the launcher starts the program only from public static void main(String[]); Java 25 also accepts an instance main or a main() without parameters, but an overload such as main(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 error

Why? 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:

  1. Phase 1: exact match or widening conversions only (e.g. int → long → double). No boxing, no varargs.

  2. Phase 2: also allow boxing/unboxing (int ↔ Integer).

  3. 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)
String

Memory 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 error

Fix 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 Bank

Rules 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 Account are happy to receive a SavingsAccount

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

final methods cannot be overridden

That's what final means

6

static methods are hidden, not overridden

They belong to the class, so there's no object to dispatch on

7

private methods and constructors are not inherited, so they cannot be overridden

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 error
import 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 error

Why 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 error

Static 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"):

  1. Compile time (overload resolution): the reference type is A. A has only greet(Object), so the compiler records a call to greet(Object).

  2. Run time (dispatch): the JVM looks for an override of greet(Object) in B. There isn't one, because B.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.5

Output after deleting the using line:

ColorPrinter::print(int) 7
ColorPrinter::print(int) 2

Without 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.5

Pythonic 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 of equals(Object o)). It becomes an overload, and collections like HashSet never call it. @Override catches 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 null to 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 or singledispatchmethod.

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.