Java INDEPENDENT TOPIC 02 – VARARGS LESSON NOTE FUNCTION OVERLOADING When
learning programming, a common function to write is one that will calculate
the average of a set of numbers. We
could write a function that will calculate the average of three numbers. We could also do one for four numbers. And another for five numbers. And so on.
Of course, this could get long! If we
really wanted to make a function that would work for any amount of numbers,
the ideal solution would be to take an array in as argument. This way, the array can contain any amount
of numbers. The
downside to requiring an array is that programmers that want to use the
function now have to do the extra work of creating the array – which is often
seen as an annoyance. SOLUTION We
can now do this in a method prototype: public
double average(double… arr) In
this situation, arr will be an array of type int. The … means that the array arr will be
automatically created based on the numbers of int arguments in the function
call. For
example, here are different functions calls that could be made to the
prototype above: double ans1 = average(82, 91, 74,
85); double ans2 = average(3, 5, 6, 6, 8,
2, 9, 12, 3, 5, 8, 2); double ans3 = average(50, 60, 40); EXAMPLE PROGRAM The
example below has a vararg function.
That function is called three different times from the main function
with different amounts of parameters. RESULT The
code above will generate the following output: SOURCE
CODE Click
here for the above code in a text file. |
|
|