Understanding of Java methods and method overloading

Posted by Concat on Mon, 04 Nov 2019 20:55:59 +0100

I. method

1. What is the method
The method is a code snippet that is referenced elsewhere, similar to the "function" in C.
2. Naming rules of methods
Must start with a letter, underscore, or '$' symbol; can include numbers, but not start with them.
3. Basic grammar of methods

//Method definition
 public static method return value method name ([parameter type parameter...]){
Method body code;
 [return return value];
}
//Method call
 Return value variable = method name (argument...);

Note: the parameters in method definition are called "formal parameters", and the parameters in method call are called "actual parameters".
4. examples
Code to add two numbers

public static void main(String[] args) {
int a = 10;
int b = 20;
        
        // Method call
int ret = add(a, b);
System.out.println("ret = " + ret);
 }
    // Method definition
public static int add(int x, int y) {
return x + y;
 }
}

Method overload

1. What is method overload
The same method name, which provides different versions of the implementation, is called method overloading.
2.
For the same add method, if there are two floating-point numbers added, or three numbers added, the method overload will be used here. The specific implementation is as follows:

 class Test { 
         public static void main(String[] args) { 
                             int a = 10; 
                             int b = 20; 
                             int ret = add(a, b); 
                             System.out.println("ret = " + ret); 

                             double a2 = 10.5; 
                             double b2 = 20.5; 
                             double ret2 = add(a2, b2); 
                             System.out.println("ret2 = " + ret2); 

                             double a3 = 10.5; 
                             double b3 = 10.5; 
                             double c3 = 20.5; 
                             double ret3 = add(a3, b3, c3); 
                             System.out.println("ret3 = " + ret3); 
             }
                 //Add two integers
                 public static int add(int x, int y) { 
                         return x + y; 
             } 
                 //Add two floating-point numbers 
                 public static double add(double x, double y) { 
                            return x + y; 
             } 
                //Add three floating-point numbers
                  public static double add(double x, double y, double z) { 
                            return x + y + z; 
         } 
}

3. Rules of overload
For the same class:
● the method name should be the same
● different parameters of the method (number or type of parameters)
● the return value type of the method does not affect overloading
Method recursion

Topics: Java