Easy java core-java

What is the difference between method overloading and method overriding?

The 30 second answer

Overloading is several methods with the same name in one class but different parameter lists; the compiler picks one at compile time from the argument types. Overriding is a subclass giving its own version of an inherited instance method with the same signature; the JVM picks it at runtime from the object's actual class. Overriding can't reduce visibility or throw broader checked exceptions, and I always add @Override so the compiler catches mistakes. Static methods are hidden, not overridden.

<!-- level: 1 --> <!-- must_know: true -->

OverloadingOverriding
WhereSame class (or inherited)Subclass of the declaring class
SignatureSame name, different parametersSame name and parameters
Return typeCan differSame or a subtype (covariant)
ChosenAt compile time, by argument typesAt runtime, by the object's class
Applies toAny method, constructors tooInstance methods only

Rules from the Java Language Specification and tutorial:

  • An overriding method cannot have weaker access (a public method can't become protected) and cannot declare broader checked exceptions.
  • static methods are hidden, not overridden: which one runs depends on the reference type.
  • private and final methods cannot be overridden.
  • @Override makes the compiler fail if the method doesn't actually override anything, which catches typos like equals(Employee other) instead of equals(Object other).
Sources (2)
  1. Java Language Specification, chapter 8: Classes (8.4.8 Inheritance, Overriding, and Hiding; 8.4.9 Overloading)docs.oracle.com
  2. Java tutorial: Overriding and hiding methodsdocs.oracle.com