Methods and overloading

When a function is used many times (repeatedly), in order to simplify the code and facilitate operation, the function is usually encapsulated and used directly. Users can not consider the implementation details of the function, but only need to know how to use the function

The function definition does not necessarily need to be used. The purpose of the definition method is that the function may be used in the subsequent use process

If it is a function that needs to be run directly, it must be run through the main function. If it is not run directly but indirectly through other methods, it is considered whether its method needs to be run directly in the main function

Relationship between methods: parallel and level relationship. All methods are in the class. A method cannot contain another method, but another method can be called

Define method format

Modifier return value type method name(parameter list){
    //Code omission  
    return result; 
}
  • Modifier: public static fixed writing method

  • Return value type: the data type representing the result of the method operation. After the method is executed, the result is returned to the caller

  • Parameter list: unknown data of the method during operation, which is passed when the caller calls the method

  • Return: bring the result of the method execution to the caller. After the method is executed to return, the overall method operation ends

Tip: return results; In the development of the "result" here, we correctly call it the return value of the method

//Definition method
public static void fire() {
    System.out.println("Prepare to fire five shells");
    System.out.println("Fire the first shell* * * *");
    System.out.println("Fire the second shell* * * *");
    System.out.println("Fire the third shell* * * *");
    System.out.println("Fire the fourth shell* * * *");
    System.out.println("Fire the fifth shell* * * *");
    System.out.println("Firing five shells is over");
}
//Used in the main method
public static void main(String[] args) {
    System.out.println("The game begins...");
    System.out.println("I saw a monster...Blood toothed wild boar...");
    //Call the method to fire shells
    fire();
    System.out.println("...The blood toothed wild boar was knocked down...");
}

Definition method considerations

  • Definition location: definitions cannot be nested outside methods in a class

  • Method must be defined before use

  • void indicates that there is no return value. You can omit return or write return separately

  • You cannot write code after return. Return means that the method ends. All subsequent codes will never be executed. It is invalid code

  • The parameters in () when defining a method are called formal parameters, and the parameters passed when calling the method are called actual parameters

  There are three forms of calling methods

  • Direct call: direct write method name call

    public static void main(String[] args) {    
        print();
    }
    public static void print() {
        System.out.println("Method called");
    }

  • Assignment call: call a method, define a variable in front of the method, and receive the return value of the method

    public static void main(String[] args) {    
        int sum = getSum(5,6);
        System.out.println(sum);
    }
    public static int getSum(int a,int b) {
        return a + b;
    }

  • Output statement invocation: invoke method in output statement

    public static void main(String[] args) {    
        System.out.println(getSum(5,6));
    }
    public static int getSum(int a,int b) {
        return a + b;
    }
    • matters needing attention

      A void method with no return value type cannot be called with an output statement. Because there is no result after the method is executed, nothing can be printed

      public static void main(String[] args) {
          //  Error, cannot call void type method with output statement
          System.out.println(printHello());
      }
      public static void printHello() {
          System.out.println("Hello");
      }

Method overloading

It means that more than one method with the same name is allowed in the same class, as long as their parameter list is different, which is different from modifier and return

The return value is independent of the type.

Parameter list: different numbers, data types and orders.

Overloaded method call: the JVM calls different methods through the parameter list of the method.

Case 1

  Array traversal

Method parameter passing reference type

  • demand

    Using the idea of method overloading, a method is designed to compare whether two integers are the same, which is compatible with all integer types (byte,short,int,long)

  • thinking

    ① Define the compare() method to compare whether two numbers are the same. Select two int parameters for the parameters

    ② Define the corresponding overloaded method, change the corresponding parameter type, and change the parameter to two long parameters

    ③ Define all overloaded methods, two byte types and two short type parameters

    ④ Complete the method call and test the running results

  • code implementation

    Parameter passing of method

      Method parameter passing basic type

  • Test code:

    public class ArgsDemo01 {
        public static void main(String[] args) {
            int number = 100;
            System.out.println("call change Before method:" + number);
            change(number);
            System.out.println("call change After the method:" + number);
        }
    ​
        public static void change(int number) {
            number = 200;
        }
    }
    ​

  • Conclusion:

    The change of basic data type parameters and formal parameters does not affect the actual parameters

  • Basis of conclusion:

    Each method has an independent stack space in the stack memory. After the method runs, it will pop up and disappear

  • Test code

    public class ArgsDemo02 {
        public static void main(String[] args) {
            int[] arr = {10, 20, 30};
            System.out.println("call change Before method:" + arr[1]);
            change(arr);
            System.out.println("call change After the method:" + arr[1]);
        }
    ​
        public static void change(int[] arr) {
            arr[1] = 200;
        }
    }
  • conclusion

    For parameters of reference type, the change of formal parameters will affect the value of actual parameters

  • Basis of conclusion

    Referring to the parameters of the data type, the address value is passed in. In memory, two references will point to the same memory. Therefore, even if the method bounces the stack, the data in the heap memory is the result of the change

  • demand

    Design a method for array traversal, which requires that the traversal result is on one line. For example: [11, 22, 33, 44, 55]

  • thinking

    1. Because the result is required to be output on one line, you need to learn a new output statement System.out.print("content"); System.out.println("content"); Output content and wrap System.out.print("content"); Output content does not wrap System.out.println(); Play the role of line feed

    2. Define an array and initialize the array elements with static initialization

    3. Define a method to traverse the array in the general format of array traversal

    4. Modify the traversal operation with a new output statement

    5. Call traversal method

  • Test code

    public class ArgsDemo02 {
        public static void main(String[] args) {
            int[] arr = {10, 20, 30};
            System.out.println("call change Before method:" + arr[1]);
            change(arr);
            System.out.println("call change After the method:" + arr[1]);
        }
    ​
        public static void change(int[] arr) {
            arr[1] = 200;
        }
    }
    ​
  • conclusion

    For parameters of reference type, the change of formal parameters will affect the value of actual parameters

 

Array traversal

  • demand

    Design a method for array traversal, which requires that the traversal result is on one line. For example: [11, 22, 33, 44, 55]

  • thinking

    1. Because the result is required to be output on one line, you need to learn a new output statement System.out.print("content"); System.out.println("content"); Output content and wrap System.out.print("content"); Output content does not wrap System.out.println(); Play the role of line feed

    2. Define an array and initialize the array elements with static initialization

    3. Define a method to traverse the array in the general format of array traversal

    4. Modify the traversal operation with a new output statement

    5. Call traversal method

  • code implementation

    public class MethodTest3 {
        public static void main(String[] args) {
            //Define an array and initialize the array elements with static initialization
            int[] arr = {11, 22, 33, 44, 55};
    ​
            //Call method
            printArray(arr);
        }
    ​
        // Define a method to traverse the array in the general format of array traversal
        /*
            Two clear:
                Return value type: void
                Parameter: int[] arr
         */
        public static void printArray(int[] arr) {
            System.out.print("[");
            for(int x=0; x<arr.length; x++) {
                if(x == arr.length-1) {
                    System.out.print(arr[x]);
                } else {
                    System.out.print(arr[x]+", ");
                }
            }
            System.out.println("]");
        }
    }

Array maximum

  • demand

    Design a method to get the maximum value of elements in the array

  • thinking

    ① Define an array and initialize the array elements with static initialization

    ② Define a method to obtain the maximum value and the cognition and explanation of the maximum value in the array, which we have explained in the array

    ③ Call the get maximum method to receive the returned result with a variable

    ④ Output the results to the console

  • code implementation

​​​​​​​

catalogue

Define method format

Definition method considerations

  There are three forms of calling methods

Method overloading

Case 1

Parameter passing of method

  Method parameter passing basic type

  Array traversal

Method parameter passing reference type

Array traversal

Array maximum

Tags: Java

Posted on Sun, 28 Nov 2021 13:48:43 -0500 by chrischen