Cara Membuat Method/Fungsi Overloading Pada Java

Method overloading adalah suatu cara untuk memberikan nama yang sama kepada dua method yang berbeda meski dua method tersebut berada dalam class yang sama. Hal ini dapat dilakukan dengan cara membedakan tipe parameter, jumlah parameter dan susunan parameter. Untuk lebih jelasnya perhatikan contoh dibawah ini :


  1. public class MethodOverload {  
  2.   
  3. public void testOverloadedMethods() {  
  4.     System.out.printf("Square of integer 7 is %d\n", square(7));  
  5.     System.out.printf("Square of double 7.5 is %f\n", square(7.5));  
  6. }  
  7.   
  8. public int square(int intValue) {  
  9.     System.out.printf("\nCalled square with int argument: %d\n",  
  10.             intValue);  
  11.     return intValue * intValue;  
  12. }  
  13.   
  14. public double square(double doubleValue) {  
  15.     System.out.printf("\nCalled square with double argument: %f\n",  
  16.             doubleValue);  
  17.     return doubleValue * doubleValue;  
  18. }  
  19. }  
Untuk test dari class method overloading diatas adalah dibawah ini :

  1. public class MethodOverloadTest {  
  2.   
  3.  public static void main(String args[]) {  
  4.      MethodOverload methodOverload = new MethodOverload();  
  5.      methodOverload.testOverloadedMethods();  
  6.  }  
  7. }  
Maka setelah kita eksekusi akan menghasilkan output seperti dibawah ini :

  1. Called square with int argument: 7  
  2. Square of integer 7 is 49  
  3.   
  4. Called square with double argument: 7.500000  
  5. Square of double 7.5 is 56.250000 

Artikel Lainnya