Friday, April 23, 2010

Method Overloading In JAVA

In JAVA, it is legal to define two or more methods with the same name within the same class provided their parameters declarations are different. The methods are said to be overloaded, and the process is called method overloading.

By now, you must be thinking about “polymorphism”, isn’t it? That is one interface, but many methods.
Based on the parameter-type and number of parameters, the JAVA knows which method to invoke during a function call.
Here’s a sample program to demo method overloading:
//MethodOverloadingDemo
public class MethodOverloadDemo{
private void evaluate(){
//method with zero parameters
System.out.println(“evaluate: No parameters);
}
//overload evaluate with one integer parameter and return it.
private int evaluate(int oneParam){
//method with one  parameters
System.out.println(“evaluate: one int param: “ + oneParam);
return oneParam;
}
//Overload evaluate to add two integers and return their sum
private int evaluate(int param1, int param2){
//method with two parameters
System.out.println(“evaluate: (param1” + param1+ “ + param2” +param2+ “)=” + param1+ param2);
return (param1 + param2);
}
//Overload evaluate to multiply two doubles and return their product
private double evaluate(double param1, double param2){
//method with two parameters
System.out.println(“evaluate:  (param1” + param1+ “ * param2” +param2+ “)=” + param1* param2);
return (param1 * param2);
}
}
NOTE: As seen in above example, the return type of overloaded methods can also be different.
Let’s see above call in action.
public class TestOverloadedDemo{
                public static void main (String args[]){
                MethodOverloadDemo mod = new MethodOverloadDemo();
               
//test overloaded methods
                mod.evaluate();
                mod.evaluate(10);
                int intResult = mod(5 + 15);
                System.out.println(“Sum of two int params: ” + intResult);
                double doubleResult = mod(11.24 * 34.23);
                System.out.println(“Product of two double params: ” + doubleResult);
}
}

//output
evaluate: No parameters
evaluate: one int param: 10
evaluate: (5 + 15) = 20
Sum of two int params: 20
evaluate:  (11.24 * 34.23) = 384.7452
Product of two double params: 384.7452

Hope this simple explanation helps. Good Luck!


No comments:

Post a Comment

Was this information useful?