What is method overloading and overriding in Java?
In this Java tutorial we will see how Java allows you to create two methods of same name by using method overloading and method overriding. We will also touch base on how methods are bonded or called by Compiler and Java Virtual Machine and finally we will answer of popular interview questions difference between method overloading and method overriding in Java. This article is in my series of Java article which discusses about Interview e.g. Difference between Synchronized Collection and Concurrent Collection or How to Stop Thread in Java. Please let me know if you have some other interview questions and you are looking answer or reason for that and here in Javarevisited we will try to find and discuss those interview questions.
Rules of Method Overriding in Java
- Method signature must be same including return type, number of method parameters, type of parameters and order of parameters
- Overriding method can not throw higher Exception than original or overridden method. means if original method throws IOException than overriding method can not throw super class of IOException e.g. Exception but it can throw any sub class of IOException or simply does not throw any Exception. This rule only applies to checked Exception in Java, overridden method is free to throw any unchecked Exception.
- Overriding method can not reduce accessibility of overridden method , means if original or overridden method is public than overriding method can not make it protected.
Exceptions handling while overloading and overriding method in Java
While overriding a method it can only throw checked exception declared by by overridden method or any subclass of it, means if overridden method throws IOExcpetion than overriding method can throw sub classes of IOExcpetion e.g. FileNotFoundException but not wider exception e.g. Exception or Throwable. This restriction is only for checked Exception for RuntimeException you can throw any RuntimeException. Overloaded method in Java doesn’t have such restriction and you are free to modify throws clause as per your need.
AS I said one of the good example of this is overriding clone method and using return type as Actual type instead of java.lang.Object, which is suggested by Joshua Bloch in Effective Java as well. This in in-fact one of the Java best practices while implementing clone method in Java. By the way don't forget to follow these Java overloading best practices, when doing it in your project.