Monday, July 11, 2016

Method Overloading

In one class, we can define more than one method with the same name, as long as the parameter contained in those methods differ. Parameters in a method said to be different from other methods if:
  • The number is different, although the data type is same
  • The data type is different, although the number is same
  • The number and data type are different

The process of defining a method with same name is called method overloading. Consider the following two examples of method:

int divide(int a, int b) {
   return a/b;
}

double divide(double a, double b) {
   return a/b;
}

The above code is legal to be defined in a class. In this example, we define two methods with the same name, but the parameters are different. In this case, the parameters are distinguished by data type. The first divide method uses two parameters with type int, while the second method parameters use two parameters with type double.

Here is an example of a program that will show the process of method overloading in a class.

class Division {

   //Define method with two parameters with type int
   int divide(int a, int b) {
      return a/b;
   }

   //Define method with two parameters with type double
   double divide(double a, double b) {
      return a/b;
   }
}

class DemoOverload1 {

   public static void main(String[] args) {

      Division d = new Division();

      int x = d.divide(10, 4);
      double y = d.divide(10.0, 4.0);

      System.out.println("Division result for int type = " + x); 
      System.out.println("Division result for double type = " + y);
   }
}

The results will be given by the above program as follows:

Division result for int type = 2
Division result for double type = 2.5

It appears from the result above, the program will examine the arguments first. Method that is called is a method that has suit parameter with argument types that are passed.

One more thing to consider in working with method overloading is the order of parameters. Although the number and type of parameters contained in some of the same method, but if the order is different, then the method will also be considered different. For example, we have two methods. The first method has two parameters of type int and String, while the second method parameters are String and int. If the location or the order of the parameters are different, then the program will consider the method as method overloading.

2 comments: