What is the difference between method overloading and method overriding in Java, and when does each one happen?
They sound alike and they are completely different things. Overloading happens inside one class. Overriding happens between a class and a class that extends it.
Overloading happens when one class has several methods with the same name but different parameters. The compiler picks the right one at compile time, using the types of the arguments you gave it.
Overriding happens when a class that extends another class gives a different body for one of the methods that it inherited. The decision about which body runs is made at run time, using the type of the object that the variable is holding, not the type of the variable.
public class Main {
public static void main(String[] args) {
Printer printer = new LaserPrinter();
// Overloading: the compiler chooses from the argument types.
System.out.println(describe(42));
System.out.println(describe("text"));
// Overriding: the object decides which method runs.
printer.print("hello");
}
static String describe(int value) { return "an int"; }
static String describe(String value) { return "some text"; }
}
class Printer {
void print(String text) {
System.out.println("printer : " + text);
}
}
class LaserPrinter extends Printer {
@Override
void print(String text) {
System.out.println("laser : " + text);
}
}
So the rule of thumb is this. Overloading is about the arguments and is decided by the compiler. Overriding is about the object and is decided while the program is running. That is why overriding is the foundation of polymorphism, and why a program can hold a list of different objects and call the same method on all of them and get the right answer for each one.
The next question in this topic looks at a case where overriding does not happen at all.