[Java] Overload

Overload

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.

Methods with the same name

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

[Java] Overload
[Java] Overload / Override / Inheritance
Overload
Java
Java
[Java] Overload and override
Java learning (0)
Studying Java ―― 3
Java protected
[Java] Annotation
[Java] Module
Java array
Studying Java ―― 9
Java scratch scratch
Java tips, tips
Java methods
Java method
java (constructor)
Java array
[Java] ArrayDeque
java (override)
Java Day 2018
Java string
java (array)
Java static
Java serialization
java beginner 4
JAVA paid
Glossary: Overload
Studying Java ―― 4
Java (set)
java shellsort
[Java] compareTo
Studying Java -5
java (interface)
Java memorandum
☾ Java / Collection
Java array
Studying Java ―― 1
[Java] Array
[Java] Polymorphism
Studying Java # 0
java framework
Java features
[Java] Inheritance
FastScanner Java
Java features
java beginner 3
Java memo
java (encapsulation)
Java inheritance
Java basics
Decompile Java
[Java] Annotation
java notes
java beginner
Java (add2)
JAVA (Map)
[java] interface
Java9 collection
Java basics