Java method overloading (Overload)

Understanding of overloading (Overload) of

  • Why use method overloading:

    • For a similar function method, the parameter list is not the same as the method if you define a different name, too cumbersome and difficult to remember.
    • To solve this problem, the introduction of overloaded methods.
  • Overloaded definitions:

    • Multiple methods of the same name, but different argument list.
  • Do not use method overloading

    • Similar method defines three functions
      public class TestOverload {
          public static int sumOne(int a) {
              return a;
          }
          public static int sumTwo(int a, int b) {
              return a + b;
          }
          public static int sumThree(int a, int b, int c) {
              return a + b + c;
          }
      }
      View Code

       

    • Use these three methods
      public static void main(String[] args) {
          System.out.println (sumone ( . 1 ));
           // output. 1 
          
          System.out.println (sumTwo ( . 1, 2 ));
           // output. 3 
      
          System.out.println (sumThree ( . 1, 2,. 3 ));
           // output 6 
      }
      View Code

       

  • Use heavy-duty

    • Similar method defines three functions
      public class TestOverload {
          public static int sum(int a) {
              return a;
          }
          public static int sum(int a, int b) {
              return a + b;
          }
          public static int sum(int a, int b, int c) {
              return a + b + c;
          }
      }
      View Code

       

    • Use these three methods
      public static void main(String[] args) {
          System.out.println (SUM ( . 1 ));
           // output. 1 
          
          System.out.println (SUM ( . 1, 2 ));
           // output. 3 
      
          System.out.println (SUM ( . 1, 2,. 3 ));
           // output 6 
      }
      View Code

       

  • to sum up:

    • Contrast can be seen if a similar function method, you can use method overloading, so not only easy to remember, it is also convenient to call.

Guess you like

Origin www.cnblogs.com/liyihua/p/11811343.html