Hare Java uses both the number of arguments and the type of the arguments to determine which method to call.
Example :-
// Java program to demonstrate Varargs
// and overloading.
class Test
{
// A method that takes varargs(here integers).
static void fun(int ... a)
{
System.out.print("fun(int ...): " +
"Number of args: " + a.length +
" Contents: ");
// using for each loop to display contents of a
for(int x : a)
System.out.print(x + " ");
System.out.println();
}
// A method that takes varargs(here booleans).
static void fun(boolean ... a)
{
System.out.print("fun(boolean ...) " +
"Number of args: " + a.length +
" Contents: ");
// using for each loop to display contents of a
for(boolean x : a)
System.out.print(x + " ");
System.out.println();
}
// A method takes string as a argument followed by varargs(here integers).
static void fun(String msg, int ... a)
{
System.out.print("fun(String, int ...): " +
msg + a.length +
" Contents: ");
// using for each loop to display contents of a
for(int x : a)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[])
{
// Calling overloaded fun() with different parameter
fun(1, 2, 3);
fun("Testing: ", 10, 20);
fun(true, false, false);
}
}
Example :-
// Java program to demonstrate Varargs
// and overloading.
class Test
{
// A method that takes varargs(here integers).
static void fun(int ... a)
{
System.out.print("fun(int ...): " +
"Number of args: " + a.length +
" Contents: ");
// using for each loop to display contents of a
for(int x : a)
System.out.print(x + " ");
System.out.println();
}
// A method that takes varargs(here booleans).
static void fun(boolean ... a)
{
System.out.print("fun(boolean ...) " +
"Number of args: " + a.length +
" Contents: ");
// using for each loop to display contents of a
for(boolean x : a)
System.out.print(x + " ");
System.out.println();
}
// A method takes string as a argument followed by varargs(here integers).
static void fun(String msg, int ... a)
{
System.out.print("fun(String, int ...): " +
msg + a.length +
" Contents: ");
// using for each loop to display contents of a
for(int x : a)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[])
{
// Calling overloaded fun() with different parameter
fun(1, 2, 3);
fun("Testing: ", 10, 20);
fun(true, false, false);
}
}
No comments:
Post a Comment