The following code in Java uses varargs to overload methods.
final public class Main
{
private void show(int []a)
{
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+"\t");
}
}
private void show(Object...a)
{
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+"\t");
}
System.out.println("\nvarargs called");
}
public static void main(String... args)
{
int[]temp=new int[]{1,2,3,4};
Main main=new Main();
main.show(temp);
main.show(); //<-- How is this possible?
}
}
The output of the above code is as follows.
1 2 3 4
varargs called
The last line main.show(); within the main() method invokes the show(Object...a){} method which has a varargs formal parameter. How can this statement main.show(); invoke that method which has no actual arguments?
main.show() invokes the show(Object... a) method and passes a zero-length array.
Varargs allows you to have zero or more arguments, which is why it is legal to call it with main.show().
Incidentally, I'd recommend that you don't embed \n in your System.out.println statements - the ln bit in println prints a newline for you that will be appropriate for the system you're running on. \n isn't portable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With