In this post we will see the rules which needs to adhered while implementing method overriding and overloading with regards to increasing/decreasing visibility of methods of parent class in child class and throwing Checked Exceptions in child class.
Method Overriding rules
For terminology, original method is known as overridden method and new method is known as overriding method. Below rules must be followed to override a methods in Java :
- Overriding method cannot throw checked exception which is higher in hierarchy than the checked Exception thrown by overridden method. For example if overridden method throws IOException which is checked Exception, than overriding method can not throw java.lang.Exception because it comes higher in type hierarchy.
"Exception 'Exception' is not compatible with throws clause in"**** Overriding method can have Runtime Exceptions declared even if Overridden method does not throw any type of Exceptions.
- Overriding method can not reduce access of overridden method. It means if overridden method is defined as public than overriding method can not be protected or package private. Similarly if original method is protected then overriding method cannot be package-private. You can see what happens if you violate this rule in Java,
"You cannot reduce visibility of inherited method of a class".
- Overriding method can increase access of overridden method. This is opposite of earlier rule.
****According to this if overridden method is declared as protected then overriding method can be protected or public
- private, static, final methods can not be overridden.
"Cannot override the final method from Parent"
- Return type of overriding method must be same as overridden method. Changing return type of method in child class will throw compile time error
"return type is incompatible with parent class method"
Method Overloading rules
Here is the list of rules which must be followed to overload a method:
- First rule to overload a method is to change method signature. method signature is made of number of arguments, type of arguments and order of arguments if they are of different types. One can change any of these or combinations of them to overload a method in Java.
Return type of method is not part of method signature, hence changing the return type alone will not overload a method in Java. In fact, it will result in compile time error.