What is the difference between overriding and overloading, and how do you tell them apart in a piece of code?
Overriding is when a child class has a new version of a method that its parent already has. Overloading is when a class has several methods with the same name but different parameters.
public class Main {
public static void main(String[] args) {
Notifier n = new LoudNotifier();
System.out.println(n.send("hi"));
}
}
And here is the overriding version.
public class Notifier {
public String send(String message) {
return "sent: " + message;
}
}
public class LoudNotifier extends Notifier {
@Override
public String send(String message) {
return "SENT LOUDLY: " + message;
}
}
So how do you tell them apart in a piece of code? Here is the table.
the thing overriding overloading
--------------------- -------------------------- --------------------------
where the methods are one in the parent, one in several in the same class
the child
the parameters the same different
the return type the same can be different
the parent must have the method not involved
who decides the runtime the compiler
And there is one test that works almost every time. If the class has the @Override annotation on the method then it is overriding. If it does not have the annotation and the same name appears more than once in the class then it is overloading.
// Overriding. The annotation is there.
@Override
public String send(String message) { }
// Overloading. Both are in the same class and the
// parameters are different.
public String send(String message) { }
public String send(String message, boolean urgent) { }
And there is one more thing that is worth knowing about. Overloading has nothing to do with inheritance. So a class that does not extend anything can still have overloaded methods.
So the rule to remember is this. Overriding is about a child class and overloading is about the parameters in one class.
The next two questions in this topic are about why overriding changes existing callers and about a static method and an instance method with the same name.