Sunday, July 11, 2021

5 Rules of Method Overloading and Overriding in Java? Examples

Since you can either overload or override methods in Java, it's 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 the method gets overloaded. That is not uncommon and happens several times when a Java programmer tries to override equals in Java or overriding the compareTo method in Java while implementing a Comparable interface, which accepts the 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 the rules of method overloading and the rule of method overriding in Java. By the way, for those who are completely new in programming, both overloading and overriding means creating a method of the same name in either the same class or child class.

In the case of overriding, the original method in the parent class is known as the overridden method, while the new method in the child class is called the overriding method.



1. Rules of overloading a method in Java

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

1. Method Signature
The first and foremost rule to overload a method in Java is to change the method signature. the method signature is made of a number of arguments, types 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 the following code, we have changed a 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, the right way to overload a method is to change the number of arguments or types of arguments because it denotes that it offers the same functionality but the input is different. For example, the println() method of PrintStream class has several overloaded versions to accept different data types like String, int, long, float, double, boolean, etc. 

Similarly, the 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 a lot of confusion and best to be avoided, as discussed in my post about overloading best practices in Java.



2. Method Return Type
The return type of method is not part of the 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 a 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 examples of these rules,




2. Method Overriding Rules in Java 

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

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





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


Overriding method cannot throw higher checked Exception in Java



3. Visibility
The overriding method can not reduce access of overridden method. It means if the overridden method is defined as public then the overriding method can not be protected or package-private. Similarly, if the original method is protected then the 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 the visibility of inherited method of a class".

You cannot reduce the visibility of the inherited method in Java




4. Accessibility
Overriding method can increase access of overridden method. This is the opposite of the earlier rule, according to this if the overridden method is declared as protected then the 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. Types of Methods
The private, static, and final methods can not be overridden in Java. See other articles in this blog to learn why you cannot override private, static, or final methods in Java. By the way, you can hide private and static methods but trying to override the final method will result in compile-time error "Cannot override the final method from a class" as shown in the below screenshot :





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

Return Type must be same for Overriding method in Java


That’s all on Rules of method overloading and overriding in Java, It's very important to remember these rules 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, here are amazing articles equally interesting :

Thanks for reading this article so far. If you like an object-oriented programming tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are serious about learning object-oriented programming and looking for a free online course to start with then you can also check this FREE Object Oriented Programming (OOPs) for JAVA Interviews course on Udemy. It's completely free and you just need a free Udemy account to join this course. 

18 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
  3. Really Nice article, with one error: Point#6 for Overriding
    Return type for Overriding : It can be changed as covariant type in Java.

    ReplyDelete
  4. Please update the rule of the return type in method signature as

    Return type of the overridding method must be same as that of the super class or it can be a sub type of the super class return type.

    ReplyDelete
    Replies
    1. Indeed, that's true from Java 1.5 onward, known as covarient method overriding.

      Delete
  5. Please add the rule of the unchecked exception as well.

    Overidding method can throw any new unchecked exception irrespective of whether super class has thrown any exception or not.

    ReplyDelete
    Replies
    1. This is also correct, there is no restriction on throwing unchecked exception on overriding method.

      Delete
  6. In second paragraph it is mentioned that " both overloading and overriding means creating method of same name in either same class or child class " but in rules for overriding 1st rule(" A method can only be overridden in sub class, not in same class")

    Could you please clarify which one is correct??

    ReplyDelete
  7. In #2 point, Overriding method cannot throw checked Exception which is higher in hierarchy. Can you please tell me the reason for this?

    ReplyDelete
    Replies
    1. Hello @Anonymous, this is because if a code is written considering superclass in mind and only handling checked exception thrown by it then it won't be able to catch the new higher exception thrown by subclass. Since checked exception has to be handled at compile time, allowing overriding method to throw higher exception will conflict with this rule.

      e.g.

      try{
      searchFile();

      }catch(FileNotFoundException f){
      }

      if searchFile() is overridden and started throwing IOException then this code will break.

      Delete
  8. Overriding method cannot throw checked Exception which is higher in hierarchy, than checked Exception thrown by overridden method

    Could someone please explain the reason for this rule ?

    ReplyDelete
  9. Please look into the below code.

    class UNIX {
    protected final void whoAmI() {
    System.out.println("I am UNIX");
    }

    protected final void whoAmI(String name, String i) {
    System.out.println("I am " + name);
    }

    protected final void whomAmI(String i, String name) {
    System.out.println("Trial on Reversing the arguments without changing the datatypes");
    }


    }

    public class MethodOverloading {
    public static void main(String args[]) {
    UNIX unix = new UNIX();
    unix.whoAmI("Sri","Madhu");
    }
    }

    Here the output is I am Sri

    How the compiler is calling that particular method only? and why I'm not getting any error like unreachable code or something of that kind.

    Thanks In Advance.

    Regards,
    Madhu.

    ReplyDelete
    Replies
    1. Hello Madhu, it's very simple, in your case you have only two method with same name, overloaded whoAmI() and whoAmI(String name, String i). Third method name is different so it doesn't come into picture "whomAmI(String i, String name)".

      Since you are calling with two String arguments, second method is chosen over first one. simple.

      Delete
  10. very good article.Neat and clear. Also good job everyone in the comments section to improvise it. We all keep learning together :)

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.