Overloading vs Overriding and Their Rules
50 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)In an OOP round the question "overloading versus overriding" is rarely asked alone. The interviewer follows it with rules, trick cases on static and private methods, and output puzzles, to check you know who decides: the compiler or the JVM.
Comparison: signature, return type, access, exceptions, binding
Overloading means several methods in one class share a name but have different parameter lists. The compiler picks one from the argument types, so it is compile-time polymorphism.
Overriding is the other half: the same name and parameter types in a subclass, replacing the inherited method. The table puts every rule for both side by side.
Example 1 · The comparison table
Overloading OverridingWhere same class (or inherited) subclassName same sameParameters must differ must be the sameReturn type anything same or subtype (covariant)Access anything same or widerChecked exceptions anything same, narrower or nonestatic/private/final can be overloaded cannot be overriddenChosen by compiler, declared arg types JVM, actual objectPolymorphism compile-time (static) run-time (dynamic)Overloading: different parameters, compile time. Overriding: same signature, run time.
What this code does
- Each row is a possible follow-up question; the last two rows are the ones interviewers care about most.
- "Anything" for overloading means the overloads are independent methods; only their parameter lists must differ.
Must know:
- overloading: parameters must differ; return type, access and exceptions may differ freely; bound at compile time
- overriding: same parameters; return type same or a subtype; access same or wider; checked exceptions same, narrower or none; bound at run time
- changing only the return type is never a valid overload
Can static, private or final methods be overridden?
Method hiding happens when a subclass declares a static method with the same signature as a parent static method. It does not override: the declared type of the reference decides which one runs.
Static, private and final methods cannot be overridden, each for its own reason. The code compiles in every case, so it looks like overriding; the output shows the truth.
Example 2 · Private, static and final methods are not overridden
class Parent { private String secret() { return "parent secret"; }
String reveal() { return secret(); }
static String type() { return "Parent"; }
final String id() { return "P-1"; }
String greet() { return "Hello from Parent"; }}
class Child extends Parent { private String secret() { return "child secret"; }
static String type() { // hides Parent.type() return "Child"; }
// String id() { return "C-1"; } // error: id() in Child cannot override id() in Parent
@Override String greet() { // a real override return "Hello from Child"; }}
public class NotOverridden { public static void main(String[] args) { Parent p = new Child(); System.out.println(p.reveal()); System.out.println(p.greet()); System.out.println(Parent.type() + " / " + Child.type()); System.out.println(p.id()); }}parent secret Hello from Child Parent / Child P-1
What this code does
reveal()prints the parent's secret even for aChildobject: private methods are not inherited, so there is nothing to override.greet()is a real override and prints the child's text.type()is chosen by the class name you call it on (method hiding), andid()cannot be overridden because it isfinal.
A static method belongs to the class, so the declared type decides. A private method is not inherited, so a same-named method in the subclass is unrelated. A final method is locked by design: the subclass version is a compile error.
Covariant return types and @Override
A covariant return type lets an overriding method return a subtype of the parent's return type, so callers need no cast. Ticket copy() can become TrainTicket copy().
Callers of an override often want the more specific type back. The code below shows that, and what @Override adds.
Example 3 · Covariant return type
class Ticket { Ticket copy() { return new Ticket(); }
String kind() { return "ticket"; }}
class TrainTicket extends Ticket { @Override TrainTicket copy() { // covariant: returns a subtype return new TrainTicket(); }
@Override String kind() { return "train ticket"; }
String pnr() { return "PNR 4521367890"; }}
public class CovariantDemo { public static void main(String[] args) { TrainTicket t = new TrainTicket(); TrainTicket copy = t.copy(); // no cast needed System.out.println(copy.kind() + ", " + copy.pnr());
Ticket general = t; System.out.println(general.copy().kind()); }}train ticket, PNR 4521367890 train ticket
What this code does
TrainTicket.copy()returnsTrainTicket, a subtype ofTicket, so code holding aTrainTicketcan callpnr()on the copy directly.- Through a
Ticketreference the declared return type isTicket, but the call still runs the override, so the copy is a train ticket.
Changing to an unrelated type, or to a different primitive, is an error: return type long is not compatible with int.
@Override asks the compiler to confirm that a method really overrides one. Without it, a typo (shw()) or a wrong parameter type (equals(Student) instead of equals(Object)) silently creates a new method. With it, javac stops with method does not override or implement a method from a supertype.
Predict the output: overload resolution
Widening is the automatic conversion of a smaller primitive to a larger one: byte to short to int to long to float to double, and char to int. The compiler tries it before boxing.
The compiler tries three phases in order: widening, then boxing, then varargs. The first phase that works wins, and the most specific method in it is chosen.
Example 4 · Overload resolution puzzles
public class OverloadPuzzle { static String m(Object o) { return "m(Object)"; } static String m(String s) { return "m(String)"; }
static String f(long x) { return "f(long)"; } static String f(Integer x) { return "f(Integer)"; } static String f(int... x) { return "f(int...)"; }
static String g(Integer x) { return "g(Integer)"; } static String g(int... x) { return "g(int...)"; }
static String c(int x) { return "c(int)"; } static String c(Character x) { return "c(Character)"; }
public static void main(String[] args) { System.out.println(m(null)); System.out.println(m(42)); System.out.println(f(5)); System.out.println(f(Integer.valueOf(5))); System.out.println(g(5)); System.out.println(g(5, 6)); System.out.println(c('a')); }}m(String) m(Object) f(long) f(Integer) g(Integer) g(int...) c(int)
What this code does
m(null)picks the most specific match,String.m(42)has nointorlongversion, so 42 is boxed toIntegerand passed as anObject.f(5)widens tolongbefore any boxing;g(5)boxes before trying varargs;c('a')widenschartointbefore boxing toCharacter. Varargs runs only when nothing else fits, as ing(5, 6).
Must know:
m(null)withm(Object)andm(String)→ String (more specific)m(null)withm(String)andm(Integer)→ compile error: ambiguousf(5)withf(long)andf(Integer)→ long (widening beats boxing)f(5)withf(Integer)andf(int...)→ Integer (boxing beats varargs);c('a')withc(int)andc(Character)→ int
Predict the output
Which overload runs?
Predict the exact output, then read the reason.
Round 1 of 3
A double overload and an Integer overload; the argument is the int 3.
Traps: return type only, reduced visibility, declared type
Three mistakes appear again and again. Overloading by return type alone fails, weaker access fails, and a broader checked exception fails. Each gives a javac message worth recognising.
Example 5 · Trap: overloads use the declared type
class Animal { String sound() { return "..."; }}
class Dog extends Animal { @Override String sound() { return "Woof"; }}
public class DeclaredTypeTrap { static String describe(Animal a) { return "describe(Animal): " + a.sound(); } static String describe(Dog d) { return "describe(Dog): " + d.sound(); }
static String greet(Object o) { return "greet(Object)"; } static String greet(String s) { return "greet(String)"; }
public static void main(String[] args) { Animal pet = new Dog(); System.out.println(describe(pet)); System.out.println(describe(new Dog()));
Object text = "hi"; System.out.println(greet(text)); System.out.println(greet((String) text)); }}describe(Animal): Woof describe(Dog): Woof greet(Object) greet(String)
What this code does
describe(pet)picksdescribe(Animal)becausepetis declared asAnimal; inside it,a.sound()still runsDog's override. Overload choice is compile time, override choice is run time.greet(text)calls theObjectversion even though the object is aString; the cast changes the declared type and so the chosen overload.
Example 6 · The compile errors to recognise
class Q { int f(int a) {...} long f(int b) {...} } -> error: method f(int) is already defined in class Q (return type only)class P { public void show() {} } class C extends P { void show() {} } -> error: show() in C cannot override show() in P attempting to assign weaker access privileges; was publicclass P { int calc() {...} } class C extends P { long calc() {...} } -> error: return type long is not compatible with intclass P { void read() throws IOException {} }class C extends P { void read() throws Exception {} } -> error: overridden method does not throw Exception@Override void shw() {} (typo for show) -> error: method does not override or implement a method from a supertypem(null) with m(String) and m(Integer) -> error: reference to m is ambiguousReturn type only, weaker access, incompatible return, broader exception, typo, ambiguity.
What this code does
- These are the real
javacmessages; recognising them quickly is often enough to answer a "why does this not compile?" question. - Only the
@Overrideerror protects you from a mistake that would otherwise compile; that is why the annotation is worth using every time.
The subtle one compiles: overloads are chosen by the declared type of the argument. Object o = "hi"; greet(o) calls greet(Object), not greet(String). Only overriding looks at the actual object.
Fix the error
Fix the broken override
Read the real javac error, then pick the line that fixes it.
Round 1 of 3
UpiPayment overrides pay but the code will not compile.
Error
Round1.java:6: error: pay(int) in UpiPayment cannot override pay(int) in Payment
void pay(int amount) { }
^
attempting to assign weaker access privileges; was publicNext step
Check your understanding
12 quick questions