Thursday, 26 April 2018

Core Java: Method Overloading

In Java, a method (of a particular method name) can have more than one versions, each version operates on different set of parameters - known as method overloading. The versions shall be differentiated by the numbers, types, or orders of the parameters.
 
For example,
/** Testing Method Overloading */
 
public class EgMethodOverloading {
   public static void main(String[] args) {
      System.out.println(average(8, 6));     // invoke version 1
      System.out.println(average(8, 6, 9));  // invoke version 2
      System.out.println(average(8.1, 6.1)); // invoke version 3
      System.out.println(average(8, 6.1));
           // int 8 autocast to double 8.0, invoke version 3
      // average(1, 2, 3, 4)  // Compilation Error - no such method
   }
   // Version 1 takes 2 int's
   public static int average(int n1, int n2) {
      System.out.println("version 1");
      return (n1 + n2)/2;  // int
   }
   // Version 2 takes 3 int's
   public static int average(int n1, int n2, int n3) {
      System.out.println("version 2");
      return (n1 + n2 + n3)/3;   // int
   }
   // Version 3 takes 2 doubles
   public static double average(double n1, double n2) {
      System.out.println("version 3");
      return (n1 + n2)/2.0;  // double
   }
}
 
The expected outputs are:
version 1
7
version 2
7
version 3
7.1
version 3
7.05

 "boolean" Methods
 
A boolean method returns a boolean value to the caller.
Suppose that we wish to write a method called isOdd() to check if a given number is odd.
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 *  Testing boolean method (method that returns a boolean value)
 */
public class BooleanMethodTest {
   // This method returns a boolean value
   public static boolean isOdd(int number) {
      if (number % 2 == 1) {
         return true;
      } else {
         return false;
      }
   }

   public static void main(String[] args) {
      System.out.println(isOdd(5));  // true
      System.out.println(isOdd(6));  // false
      System.out.println(isOdd(-5)); // false
   }
}
 
This seemingly correct codes produces false for -5, because -5%2 is -1 instead of 1. You may rewrite the condition:
 
public static boolean isOdd(int number) {
   if (number % 2 == 0) {
      return false;
   } else {
      return true;
   }
}
 
The above produces the correct answer, but is poor. For boolean method, you can simply return the resultant boolean value of the comparison, instead of using a conditional statement, as follow:
 
public static boolean isEven(int number) {
   return (number % 2 == 0);
}
public static boolean isOdd(int number) {
   return !(number % 2 == 0);
}

No comments:

Post a Comment

Please write your view and suggestion....