In this article, I want to give a brief explanation about overriding and overloading.
Overriding and overloading happens only when the method name is the same.
To override a method, you must create a method with the same signature. The method name and the parameters together are called method signature.
To overload a method, besides the same method name, you must change method parameters type, order and/or number.
The most confusing thing about overloading methods is that when there are more than one overloaded methods, which of them are going to be called? Java looks for the following rules in order :
- Exact match by type
- Matching a superclass type
- Converting to a larger primitive type
- Converting to an autoboxed type
The rules that you should know about overriding methods are:
- Methods with the static keyword cannot be overridden.
- The access modifier must be the same or more accessible.
- The return type must be the same or a more restrictive type
- If any checked exceptions are thrown, only the same exceptions or subclasses of those exceptions are allowed to be thrown.