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 :
public
class MethodOverload {
public
void testOverloadedMethods() {
System.out.printf("Square of integer 7
is %d\n", square(7));
System.out.printf("Square of double
7.5 is %f\n", square(7.5));
}
public
int square(int intValue) {
System.out.printf("\nCalled square
with int argument: %d\n",
intValue);
return intValue * intValue;
}
public
double square(double doubleValue) {
System.out.printf("\nCalled square
with double argument: %f\n",
doubleValue);
return doubleValue * doubleValue;
}
}
Untuk
test dari class method overloading diatas adalah dibawah ini :
public
class MethodOverloadTest {
public static void main(String args[]) {
MethodOverload methodOverload = new
MethodOverload();
methodOverload.testOverloadedMethods();
}
}
Maka
setelah kita eksekusi akan menghasilkan output seperti dibawah ini :
Called
square with int argument: 7
Square
of integer 7 is 49
Called
square with double argument: 7.500000
Square
of double 7.5 is 56.250000
No comments:
Post a Comment