I encountered this question in the latest interview, a senior position into top-tier international company couple days ago. Not the tough one but you may need to know. Let's get it, once and for all.
Definitions
Overriding: when the method signature (name and parameters) are the same in the superclass and the child class, it's called Overriding.
Overloading: When two or more methods in the same class have the same name but different parameters, it's called Overloading.
Differences
Examples
Overloading example:
As you can see, we have 3 versions of method add(). We are overloading the method add() here.
Output
3 6 10
Overriding example:
Output
Moew meow
Here speak() method of class Cat is overriding the speak() method of Animal.
Java (after version 5) supports covariant return types for overridden methods. This means an overridden method may have a more specific return type. That is, as long as the new return type is assignable to the return type of the method you are overriding, it's allowed.
You can override a method with the same signature but return a subclass of the object returned.
In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature from the superclass.
Comments