We can overload a method with a variable-length argument.
For example, the following program overloads myTest()
three times:
// Varargs and overloading. public class Main { static void myTest(int ... v) { System.out.print("myTest(int ...): " + "Number of args: " + v.length + " Contents: "); for(int x : v) { System.out.print(x + " "); }/*from w w w.j a v a2 s .c o m*/ System.out.println(); } static void myTest(boolean ... v) { System.out.print("myTest(boolean ...) " + "Number of args: " + v.length + " Contents: "); for(boolean x : v) { System.out.print(x + " "); } System.out.println(); } static void myTest(String msg, int ... v) { System.out.print("myTest(String, int ...): " + msg + v.length + " Contents: "); for(int x : v) { System.out.print(x + " "); } System.out.println(); } public static void main(String args[]) { myTest(1, 2, 3); myTest("Testing: ", 10, 20); myTest(true, false, false); } }
We can overload a varargs method in two ways:
A varargs method can be overloaded by a non-varargs method.
Java will invoke the method with single parameter first.
public class Main { // calculate average public static double average(double... numbers) {/*from ww w. j a v a 2 s . c om*/ double total = 0.0; // calculate total using the enhanced for statement for (double d : numbers) total += d; return total / numbers.length; } public static void main(String[] args) { double d1 = 10.0; double d2 = 20.0; double d3 = 30.0; double d4 = 40.0; System.out.printf("d1 = %.1f%nd2 = %.1f%nd3 = %.1f%nd4 = %.1f%n%n", d1, d2, d3, d4); System.out.printf("Average of d1 and d2 is %.1f%n", average(d1, d2)); System.out.printf("Average of d1, d2 and d3 is %.1f%n", average(d1, d2, d3)); System.out.printf("Average of d1, d2, d3 and d4 is %.1f%n", average(d1, d2, d3, d4)); } }