What are the restrictions placed on method overloading in java?


When a class has two or more methods by the same name but different parameters, at the time of calling based on the parameters passed respective method is called (or respective method body will be bonded with the calling line dynamically). This mechanism is known as method overloading.

Example

 Live Demo

class Test{
   public int division(int a, int b){
      int result = a/b;
      return result;
   }
   public double division (float a, float b){
      double result = a/b;
      return result;
   }
}
public class OverloadingExample{
   public static void main(String args[]){
      Test obj = new Test();
      System.out.println("division of integers: "+obj.division(100, 40));
      System.out.println("division of floating point numbers: "+obj.division(214.225f, 50.60f));
   }
}

Output

division of integers: 2
division of floating point numbers: 4.233695983886719

Rules to be followed for method overloading

While overloading you need to keep the following points in mind −

  • Both methods should be in the same class.
  • The name of the methods should be same but they should have different number or, type of parameters.

If the names are different they will become different methods and, if they have same name and parameters a compile time error will be thrown saying “method already defined”.

Example

class Test{
   public int division(int a, int b){
      int result = a/b;
      return result;
   }
   public double division (int a, int b){
      double result = a/b;
      return result;
   }
}

Compile time error

OverloadingExample.java:6: error: method division(int, int) is already defined in class Test
public static double division (int a, int b){
                     ^
1 error

In overriding, if the both methods follow above two rules they can −

  • Have different return types.

Example

class Test{
   public int division(int a, int b){
      int result = a/b;
      return result;
   }
   public void division (float a, float b){
      double result = a/b;
      System.out.println("division of floating point numbers: "+result);
   }
}
  • Have different access modifiers −
class Test{
   public int division(int a, int b){
      int result = a/b;
      return result;
   }
   private void division (float a, float b){
      double result = a/b;
      System.out.println("division of floating point numbers: "+result);
   }
}
  • Can throw different exceptions −
class Test{
   public int division(int a, int b)throws FileNotFoundException{
      int result = a/b;
      return result;
   }
   private void division (float a, float b)throws Exception{
      double result = a/b;
      System.out.println("division of floating point numbers: "+result);
   }
}

Updated on: 30-Jul-2019

724 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements