简体   繁体   中英

Varargs vs method overloading

Method overloading is used to perform tasks of differnt type under the restriction of no of variables passed (ie...,each of such has differnt types of code depending on parameters passed). but what is the necessity of varargs ie..,we can pass multiple arguments .but how can we make the difference of code for no of variables passed ie.., multiple tasks under multiple arguments?

varargs are a short hand for passing an array. eg instead of writing

public static void main(String[] args) {
   for(String arg : args)
       System.out.println(arg);

you can instead write

public static void main(String... args) {
   for(String arg : args)
       System.out.println(arg);

the main difference is that the caller can now write

main("hello", "world");

VARARGS is used when there is an indeterminate number of parameters (objects) needed for a method. A canonical example is Java's Formatter .

An example is as such:

String.format("My name is %s", myName);
String.format("My name is %s %s", myFirstName, myLastName);
String.format("My name is %s %s and I am %d years old", myFirstName, myLastName, myAge);

Lets suppose you want to calculate volume of quadrilateral. First scenario is calculating area for rectangle, it will require three parameters. second scenario will be if you are calculating area for cube that requires only one parameter and third scenario could be no value is passed. Lets see through an example: For illustration purpose only

Class Volume(){

Volume(){
this (-1, -1, -1)
}
Volume(int x){
this (x, x, x)
}
volume(int x, y, z)
length = x;
breadth = y;
height = z;
}
public int getVolume(){
return length*breadth*height
}

This is known scenario and no other options are possible, but if you are unsure of number of arguments, we use varags. In the above situation we did not use varags as they are less efficient and consume more space and its more dangerous in the sense it lets user to pass as many arguments as they want which is not the case in the above example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM