Overloading vs overriding

Junior Always asked 6 min

On this page

The question

What is the difference between overloading and overriding?

30-second answer

Overloading is several methods with the same name and different parameters; the compiler picks one from the declared types it sees. Overriding is a subclass redefining an inherited method with the same signature; the JVM (Java Virtual Machine) picks the version from the object's class at runtime. Overloading is compile-time polymorphism, overriding is runtime polymorphism.

Understand it

Which greet and which speak run?

Predict

Animal a = new Dog(); then greet(a). There are overloads greet(Animal) and greet(Dog), and Dog overrides speak().

What does greet(a) print?
View as text

Animal a = new Dog(); then greet(a). There are overloads greet(Animal) and greet(Dog), and Dog overrides speak(). The drawing shows the variable a of type Animal pointing at a Dog object, the two greet overloads and the two speak methods. The learner first predicts the output.

At compile time javac only knows that a has type Animal, so it picks greet(Animal). An arrow joins a to greet(Animal); greet(Dog) fades.

At runtime greet(Animal) calls a.speak(). The object is a Dog, so the JVM runs Dog's speak(). An arrow joins greet(Animal) to speak() in Dog; speak() in Animal fades.

It prints greet(Animal): Woof. Overloads follow the declared type; overrides follow the object.

Animal a = new Dog(); then greet(a). There are overloads greet(Animal) and greet(Dog), and Dog overrides speak(). The drawing shows the variable a of type Animal pointing at a Dog object, the two greet overloads and the two speak methods. The learner first predicts the output.

At compile time javac only knows that a has type Animal, so it picks greet(Animal). An arrow joins a to greet(Animal); greet(Dog) fades.

At runtime greet(Animal) calls a.speak(). The object is a Dog, so the JVM runs Dog's speak(). An arrow joins greet(Animal) to speak() in Dog; speak() in Animal fades.

It prints greet(Animal): Woof. Overloads follow the declared type; overrides follow the object.

Takeaway: The compiler picks the overload from the variable's type; the JVM picks the override from the object's class. One call can use both.

How the JVM finds the override

Step by step

javac sees a.speak() on a variable of type Animal and records a virtual call to Animal's speak().

Step 1 of 5
View as text

The code is Animal a = new Dog(); a.speak(). The drawing shows the variable a, a Dog object, the Dog class and Dog's method table with three slots: toString, speak and eat.

javac sees a.speak() on a variable of type Animal and records a virtual call to Animal's speak(). A badge shows the recorded call.

At runtime the JVM follows a to the object it points to. The object is a Dog. An arrow joins a to the Dog object.

The object's header points to its class, Dog. An arrow joins the object to the Dog class.

In HotSpot, Dog's method table keeps speak() in the same slot as Animal's, filled with Dog's override. The speak row is highlighted; eat still points to Animal's version.

The JVM runs Dog.speak(). Java only requires this behavior; the method table is how HotSpot implements it.

The code is Animal a = new Dog(); a.speak(). The drawing shows the variable a, a Dog object, the Dog class and Dog's method table with three slots: toString, speak and eat.

javac sees a.speak() on a variable of type Animal and records a virtual call to Animal's speak(). A badge shows the recorded call.

At runtime the JVM follows a to the object it points to. The object is a Dog. An arrow joins a to the Dog object.

The object's header points to its class, Dog. An arrow joins the object to the Dog class.

In HotSpot, Dog's method table keeps speak() in the same slot as Animal's, filled with Dog's override. The speak row is highlighted; eat still points to Animal's version.

The JVM runs Dog.speak(). Java only requires this behavior; the method table is how HotSpot implements it.

Takeaway: The call names a method of the declared type; the object's class decides which body runs. HotSpot finds it through a per-class method table.

Two choices for one callAt compile time the compiler uses declared types to pick the overload. At runtime the JVM uses the object's class to pick the override, and that method runs.A method callCompile time:declared types pickthe overloadRuntime: the object'sclass picks theoverrideThat method bodyruns
Two choices for one callAt compile time the compiler uses declared types to pick the overload. At runtime the JVM uses the object's class to pick the override, and that method runs.A method callCompile time:declared types pickthe overloadRuntime: the object'sclass picks theoverrideThat method bodyruns
Two choices for one call: the compiler's, then the JVM's

In code

class Animal { String speak() { return "generic sound"; } }
class Dog extends Animal { @Override String speak() { return "Woof"; } }

static String greet(Animal a) { return "greet(Animal): " + a.speak(); }
static String greet(Dog d)    { return "greet(Dog): " + d.speak(); }

Animal a = new Dog();
String s = greet(a);   // "greet(Animal): Woof"
Overload chosen by type, override chosen by object
class Point {
    int x;
 Wrong     public boolean equals(Point o) { return o != null && x == o.x; }  // overload: HashSet never calls it
 Right     @Override public boolean equals(Object o) {                        // the real override
        return o instanceof Point p && x == p.x;
    }
    @Override public int hashCode() { return Integer.hashCode(x); }
}
An equals(Point) overload is not the override collections call
How greet resolves when an Animal variable holds a DogThe variable a has type Animal and holds a Dog. The compiler reads the type and picks greet of Animal. Inside it, the JVM reads the object and runs the speak method of Dog, so the output is greet Animal Woof.by typeby objecta: type Animal,object Doggreet(Animal)Dog's speak()greet(Animal): Woof
How greet resolves when an Animal variable holds a DogThe variable a has type Animal and holds a Dog. The compiler reads the type and picks greet of Animal. Inside it, the JVM reads the object and runs the speak method of Dog, so the output is greet Animal Woof.by typeby objecta: type Animal,object Doggreet(Animal)Dog's speak()greet(Animal): Woof
How greet(a) resolves when an Animal variable holds a Dog
static String f(long x)    { return "long"; }
static String f(Integer x) { return "Integer"; }
static String f(int... x)  { return "varargs"; }

String r = f(5);   // "long": int widens to long before it would be boxed to Integer
Overload resolution tries widening first, then boxing, then varargs

Solve it

Predict the output of three calls through a parent variable

Parent and Child both declare a static method who(), an instance method me() and a field name. With Parent p = new Child(), what do p.who(), p.me() and p.name return? Explain each answer.

  1. Split every call into two choices. The compiler binds by the variable’s type, Parent. Only an overridden instance method is chosen again at runtime by the object.
  2. who() is static. Static methods belong to the class and are hidden, not overridden, so the compiler’s choice stands: “Parent”.
  3. me() is an instance method that Child overrides. Dynamic dispatch looks at the object, a Child, and runs Child.me(): “Child”.
  4. name is a field. Fields are never polymorphic; the declared type picks Parent.name: “Parent”.
  5. Check. Only overridable instance methods dispatch at runtime. Static, private and final methods, and fields, are decided at compile time.
class Parent {
    String name = "Parent";
    static String who() { return "Parent"; }
    String me() { return "Parent"; }
}
class Child extends Parent {
    String name = "Child";                       // hides Parent.name
    static String who() { return "Child"; }      // hides, does not override
    @Override String me() { return "Child"; }
}

Parent p = new Child();
p.who();   // "Parent"  compile time, by type (call it as Parent.who())
p.me();    // "Child"   runtime, by object
p.name;    // "Parent"  compile time, by type
Only the overridden instance method follows the object

How to answer

  • Overloading: same name, different parameter lists, chosen by the compiler from declared types.
  • Overriding: same signature in a subclass, chosen at runtime from the actual object.
  • A different return type alone does not make an overload.
  • Static, private and final methods cannot be overridden.
  • Add @Override so the compiler catches a signature typo.

Common mistakes

  • Saying the overload is chosen from the object's runtime type; the compiler picks it from the declared types.
  • Claiming a static method can be overridden; a static method with the same signature only hides the parent's.

Follow-up questions

What is the difference between compile-time and runtime polymorphism?

Compile-time polymorphism is overloading: javac picks a method from the declared types of the arguments, and that choice is fixed in the bytecode. Runtime polymorphism is overriding: the JVM picks the method from the object's class every time the call runs.

  • Compile time: overloads, chosen by declared types.
  • Runtime: overrides, chosen by the object's class.
  • One call can use both, as greet(a) with an Animal variable holding a Dog shows.

See it in the infographic: Which greet and which speak run?

How does the JVM pick which overridden method to run?

The bytecode names the method of the declared type, like Animal's speak(). At runtime the JVM takes the actual object, follows its header to its class and runs that class's version, the most specific override. HotSpot makes this fast with a per-class method table, the vtable, but Java only specifies the behavior.

  • The call site names a method; the object picks the implementation.
  • The lookup starts at the object's class and walks up through its parents.
  • vtables are a HotSpot implementation detail, not a language rule.

See it in the infographic: How the JVM finds the override

With overloads f(Object) and f(String), which one does f(null) call?

f(String). null fits both, and the compiler picks the most specific overload, and String is a subtype of Object. With f(String) and f(Integer) instead, f(null) does not compile, because neither is more specific.

  • The compiler picks the most specific applicable overload.
  • Two unrelated candidates make the call ambiguous.
static void f(Object o) { System.out.println("Object"); }
static void f(String s) { System.out.println("String"); }
f(null); // String

See it in the infographic: Which greet and which speak run?

If Animal and Dog both declare static String kind(), what does a.kind() run for Animal a = new Dog()?

Animal's kind(). Static methods are not overridden; the one in Dog only hides Animal's. The call is bound at compile time to the declared type, Animal, so the object does not matter.

  • Static methods are hidden, not overridden.
  • The declared type decides, as it does for overloads.
  • Call static methods through the class name.
Animal a = new Dog();
a.kind();   // Animal's kind(): static, chosen by type
Dog.kind(); // Dog's kind()

See it in the infographic: How the JVM finds the override

What rules must an overriding method follow?

The same name and parameter types, and a return type that is the same or a subtype. It cannot narrow visibility, so a public method stays public, and it cannot throw broader checked exceptions. Final, static and private methods cannot be overridden.

  • Same signature; a covariant return type is allowed.
  • Visibility can widen, never narrow.
  • Checked exceptions can narrow, never widen.
  • Add @Override so mistakes fail to compile.

See it in the infographic: How the JVM finds the override

Can you override a private method?

No. A private method is not inherited, so a subclass method with the same signature is a new, unrelated method, and putting @Override on it is a compile error.

Can two methods differ only by return type?

No. The compiler picks an overload from the arguments at the call site, so two methods that differ only in return type would be ambiguous, and the class does not compile.

Are fields polymorphic like methods?

No. A field is resolved from the reference's declared type. With Animal a = new Dog() and a name field in both classes, a.name reads Animal's field; only methods are dispatched at runtime.

Check yourself

1. Animal a = new Dog(); and there are overloads greet(Animal) and greet(Dog). Which one does greet(a) call?
Show answers
  • greet(Animal): Correct. Overloads are chosen at compile time from the variable's type, Animal.
  • greet(Dog): Incorrect. The object is a Dog, but the compiler only sees the type Animal.
  • It does not compile: Incorrect. greet(Animal) applies, so the call compiles.
2. Animal and Dog both declare a field name. With Animal a = new Dog();, whose field does a.name read?
Show answers
  • Animal's: Correct. Fields are resolved from the declared type and never dispatched.
  • Dog's: Incorrect. Only methods are dispatched to the object's class at runtime.
  • It does not compile: Incorrect. Hiding a field is legal, although confusing.
3. Which methods can a subclass override?Choose 2
Show answers
  • A public, non-final instance method: Correct. Inherited instance methods that are not final can be overridden.
  • A protected, non-final instance method: Correct. protected methods are inherited, so they can be overridden.
  • A private method: Incorrect. Private methods are not inherited, so there is nothing to override.
  • A static method: Incorrect. A static method is hidden by the subclass, not overridden.
  • A final method: Incorrect. final exists to forbid overriding.