Sub topic 8
Overloading Is Not Overriding
Two Java features have similar names and look alike on the page: overloading and overriding. Both let several methods share one name. They work in different ways, though, and they run at different moments. If you mix them up, your program can call a method you did not expect, and it will do so without any error message.
This chapter shows how each one works, how Java chooses between them, and how to avoid the mistakes beginners make most often.
Two Words, Two Ideas
Overloading means one class has several methods with the same name but different parameter lists. A parameter list is the number, types, and order of the inputs a method takes. The method's name plus its parameter list is called its signature.
Overriding means a subclass provides its own version of a method it inherited. The method has the same signature as the one in the superclass. You saw this in earlier chapters.
Here is the short version:
- Overloading uses the same name with a different signature. It gives you a new method.
- Overriding uses the same name with the same signature. It replaces an inherited method's behavior.
Overloading: A Worked Example
Here is a class with three methods named add.
public class Main {
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
System.out.println(add(2, 3)); // 5
System.out.println(add(2.5, 1.5)); // 4.0
System.out.println(add(1, 2, 3)); // 6
}
}Each call matches a different add. The compiler chooses which one. The compiler is the tool that turns your code into a program, and it runs before your program does. It looks at the arguments you pass, checks their types, and finds the best matching signature.
When Each Choice Is Made
The most important difference between the two features is timing.
- Overloading is resolved at compile time. The compiler picks the method using the declared types of the arguments. A declared type is the type written in the variable's declaration.
- Overriding is resolved at runtime. The JVM picks the method using the runtime type of the object. The runtime type is the actual class of the object, the one created with
new. The JVM (Java Virtual Machine) is the program that runs your compiled code.
A single method call goes through both steps, one after the other. First the compiler fixes the signature. Then the JVM finds the version of that signature that belongs to the object's real class.
Seeing Both Steps in One Program
This program has an overload and an override in it.
class Printer {
void print(Object o) {
System.out.println("Printer: Object");
}
void print(String s) {
System.out.println("Printer: String");
}
}
class FancyPrinter extends Printer {
@Override
void print(Object o) {
System.out.println("FancyPrinter: Object");
}
}
public class Main {
public static void main(String[] args) {
Printer p = new FancyPrinter();
Object o = "hello";
p.print(o); // FancyPrinter: Object
p.print("hi"); // Printer: String
}
}Let's trace p.print(o).
- The compiler sees that
ois declared asObject. It does not care that the object is really aString. It picksprint(Object). - At runtime, the JVM sees that
prefers to aFancyPrinter.FancyPrinteroverridesprint(Object), so its version runs.
Now trace p.print("hi").
- The argument
"hi"has the declared typeString. The compiler picksprint(String), because it is the closest match. - At runtime the object is still a
FancyPrinter. ButFancyPrinterdoes not overrideprint(String). So the inheritedPrinterversion runs.
A Common Trap: Overloading When You Meant to Override
Suppose you want a subclass to change how it greets strings. You write this:
class Greeter {
void greet(Object o) {
System.out.println("Greeter: Object");
}
}
class LoudGreeter extends Greeter {
void greet(String s) {
System.out.println("LoudGreeter: String");
}
}
public class Main {
public static void main(String[] args) {
Greeter g = new LoudGreeter();
g.greet("hi"); // Greeter: Object
LoudGreeter lg = new LoudGreeter();
lg.greet("hi"); // LoudGreeter: String
}
}greet(String) does not have the same signature as greet(Object). So LoudGreeter did not override anything. It added a new overload.
When you call through g, the compiler only looks at the methods of the declared type, Greeter. Greeter has only greet(Object), so that is the one picked. LoudGreeter never overrode it, so the Greeter version runs. When you call through lg, the compiler can see both methods and picks the better match, greet(String).
This bug gives no error and no warning. The program simply runs the wrong method.
Edge Cases in Choosing an Overload
Passing null
null fits any reference type. So which overload does it pick? The compiler chooses the most specific one. A type is more specific when it is a subtype of the other. String is a subtype of Object, so String wins.
public class Main {
static void show(Object o) {
System.out.println("Object");
}
static void show(String s) {
System.out.println("String");
}
public static void main(String[] args) {
show(null); // String
}
}If you add static void show(Integer i), the call show(null) stops compiling. String and Integer are both more specific than Object, but neither is a subtype of the other. The compiler reports that the call is ambiguous, meaning it cannot choose. You fix it with a cast, for example show((String) null).
Casting changes the overload
A cast changes the declared type of an expression, so it changes which overload the compiler picks. In the Printer example, p.print((Object) "hi") calls print(Object), and FancyPrinter's version runs.
Side-by-Side Comparison
| Question | Overloading | Overriding |
|---|---|---|
| Where are the methods? | Usually the same class (or inherited plus new) | Superclass and subclass |
| Signature | Must differ | Must be the same |
| Who decides which runs? | The compiler | The JVM |
| When? | Compile time | Runtime |
| Based on | Declared types of the arguments | Runtime type of the object |
| Does `@Override` apply? | No, it causes an error | Yes, and you should use it |
Exercises
Exercise
Using the Printer and FancyPrinter classes from this chapter, what do these lines print? Printer p = new FancyPrinter(); String s = "a"; p.print(s); p.print((Object) s);
Show answer
The first call prints "Printer: String". The declared type of s is String, so the compiler picks print(String), and FancyPrinter does not override it. The second prints "FancyPrinter: Object". The cast makes the compiler pick print(Object), and FancyPrinter overrides that one.
Exercise
Class A has void run(int x). Class B extends A and declares void run(long x). Is this overloading or overriding? With A a = new B(); which method does a.run(5) call?
Show answer
It is overloading, because the parameter types differ (int versus long). The compiler only sees A's methods through the reference a, so it picks run(int), and A's version runs.
Exercise
Why does adding @Override to LoudGreeter.greet(String) help, even though the program already compiles without it?
Show answer
@Override tells the compiler you intend to override an inherited method. greet(String) does not match any method in Greeter, so the compiler reports an error. That shows you the method is really an overload, which you would otherwise find only from wrong output at runtime.