In Java, even methods that work the same have different numbers of arguments, and you have to create methods that match the number of arguments. At this time, how should I give the method name? Of course, it is possible to name them so that there are no duplicates, but if there are as many statements as there are arguments, it will be difficult to remember them. In this case, ** overload ** is useful.
See the program below. The max () method returns the larger of the two int variables.
class Max{
static int max(int x, int y){
if(x>y)
return x;
return y;
}
}
Consider extending this to return a larger one for a double variable. You will have to create a new method that corresponds to the double type argument, but the key is what to do with the method name at this time. In Java, method names can be freely assigned by programmers according to the same rules as variable names. Since processing int type values and processing double type values have different argument types and return types, it is not strange to distinguish between method names such as doubleMax (). However, from the standpoint of using the method, the process of "returning the largest value among the arguments even if the number is different" does not change, so give various names depending on the number of arguments and the type of type. It should be easier to use if they have the same name, even if they have different numbers of arguments, rather than creating and selecting them accordingly. Defining a method with the same name with a different number of arguments is called ** overload **. Overloading eliminates the need for programmers to find the method that corresponds to the argument, and allows the program to be written by focusing on the "function" of the method itself.
class Max{
static int max(int a, int b){
if(a>b)
return a;
return b;
}
static double max(double a, double b){
if(a>b)
return a;
return b;
}
}
Recommended Posts