Wednesday, May 7, 2014

Method Overloading: Variable number of Arguments

One of the rules of method overloading is different number of arguments in the overloaded method definitions
Consider
public void printInt(int a)
public void printInt(int a, int b)
public void printInt(int a, int b, int c)
public void printInt(int...x) /*Ah! tricky one*/
All above methods are overloaded. But what will be the output for this code?
printInt(1,2,3);
My first guess was public void printInt(int...x) as it more generalized method definition. But, it's wrong answer.
First, the compiler will search for an overloaded method with exact number of arguments. If not found, it will go for method with variable number of arguments.

public class Test {
public void printInt(int a) {
System.out.println("Method with one argument");
}
/*public void printInt(int a, int b) {
System.out.println("Method with two arguments");
}*/
public void printInt(int a, int b, int c) {
System.out.println("Method with three arguments");
}
public void printInt(int...x) {
System.out.println("Method with variable number of arguments");
}
public static void main(String[] args) {
Test t = new Test();
t.printInt(1);
t.printInt(1,2);
t.printInt(1,2,3);
t.printInt(1,2,3,4);
t.printInt(1,2,3,4,5);
}
}
/*
Output:
Method with one argument
Method with variable number of arguments
Method with three arguments
Method with variable number of arguments
Method with variable number of arguments
*/

0 comments:

Post a Comment