Thursday, September 13, 2012

Rules of Method Overloading and Overriding in Java

Overloading and overriding rule in JavaSince you can either overload or override methods in Java, its important to know what are the rules of overloading and overriding in Java. any overloaded method or overridden method must follow rules of method overloading and method overriding to avoid compile time error and logical runtime errors;  where you intend to override a method but method get overloaded. That is not uncommon and happen several times when Java programmer tries to override equals in Java or  overriding compareTo method in Java while implementing Comparable interface, which accepts Object type of argument. From Java 5 onwards which introduces @Override annotation along with Enum, Generics and varargs method you can completely avoid that problem. Anyway, let's see rules of method overloading and rule of method overriding in Java. By the way, for those who are completely new in programming, both overloading and overriding means creating method of same name in either same class or child class. In case of overriding, the original method in parent class is known as overridden method, while new method in child class is called overriding method.


Rule of overloading a method in Java
Here is the list of rule which needs to be followed to overload a method in Java :

Rules of method overloading and overriding in Java1) First and foremost rule to overload a method in Java 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. You can change any of these or combinations of them to overload a method in Java. For example, in following code, we have changed number of arguments to overload whoAmI() method in Java :
class UNIX {
    
    protected final void whoAmI() {
        System.out.println("I am UNIX");
    }
    
    protected final void whoAmI(String name){
        System.out.println("I am " + name);
    }
    
}

By the way, right way to overload a method is to change the number of argument or type of argument because it denotes that it offer same functionality but input is different. For example println() method of PrintStream class has several overloaded version to accept different data types e.g. String, int, long, float, double, boolean etc. Similarly, EnumSet.of() method is overloaded to accept one, two or more values. The third way to overload method by changing the order of argument or type of argument creates lot of confusion and best to be avoided, as discussed in my post about overloading best practices in Java.

2) Return type of method is not part of method signature, so just changing the return type will not overload a method in Java.  In fact, just changing the return type will result in compile time error as "duplicate method X in type Y. Here is a screenshot of that error in Eclipse :


See what is method overloading in Java for code example of these rules,



Method Overriding Rules in Java
Overriding is completely different than overloading and so it's rules are also different. For terminology, original method is known as overridden method and new method is known as overriding method. Following rules must be followed to correctly override a method in Java :

1) A method can only be overridden in sub class, not in same class. If you try to create two methods with same signature in one class compiler will complain about it saying "duplicate method in type Class", as shown in following screenshot :



2) Overriding method cannot throw checked Exception which is higher in hierarchy, than checked
Exception thrown by overridden method. For example if overridden method throws IOException or ClassNotfoundException, which are checked Exception, than overriding method can not throw java.lang.Exception because it comes higher in type hierarchy (it's super class of IOException and ClassNotFoundExcepiton). If you do so, compiler will catch you as seen in following image :
Overriding method cannot throw higher checked Exception in Java


3) 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, as seen in this screenshot it will throw compile time error saying "You cannot reduce visibility of inherited method of a class".
You cannot reduce the visibility of the inherited method in Java


4) Overriding method can increase access of overridden method. This is opposite of earlier rule, according to this if overridden method is declared as protected than overriding method can be protected or public. Here is an example to see that it's allowed in Java :
You can increase visibility of overridden method in Java


5) private, static and final method can not be overridden in Java. See other articles in this blog to learn why you cannot override private, static or final method in Java. By the way, you can hide private and static method but trying to override final method will result in compile time error "Cannot override the final method from a class" as shown in below screenshot :




6) Return type of overriding method must be same as overridden method. Trying to change return type of method in child class will throw compile time error "return type is incompatible with parent class method" as shown in following screenshot.
Return Type must be same for Overriding method in Java


That’s all on Rules of method overloading and overriding in Java, Its very important to remember these rule to correctly overload and override any method in Java. Also remember to use @Override annotation to accidentally overloading a method, instead of overriding it.

If you like this article and love to read Java articles, You will these amazing articles equally interesting :

5 comments:

  1. plz upload clear information of method signature

    ReplyDelete
  2. Please also add rules of return type in method singnature.

    ReplyDelete
    Replies
    1. Hello @Anonymous, thanks for your suggestion, Updated article to include importance of return type while overriding method in Java as well.

      Delete

Java67 Headline Animator