Java from entry to factory method definition, call overload to pass parameters

Time:2022-1-22

catalogue

Definition of method

Basic format of method:

Basic syntax of method:

Method call

What is a method call?

How do I call a method?

Method overload

What is method overloading

Rules for overloaded methods:

Recursive call:

What is recursion?

What are the benefits of recursion?

The recursive structure consists of two parts:

Homework after class


Hello, everyone. I’m brother laiping. Today I bring the methods in Java. This chapter is very important. I hope you can gain something from me, and I also hope the big guys can correct more! thank you!

Definition of method

Java method is similar to functions in other languages. It is a code fragment used to complete specific functions.

For example:

System.out.println()

The above is a common piece of code in Java

Of which:

Println () is a method.

System is a system class.

Out is the standard output object.

Basic format of method:

Modifier return value type method name (parameter type parameter name){
 ...  Method body
 ...  Return return value;
 }

Basic syntax of method:

Generally, defining a method includes the following syntax:

Method contains a method header and a method body. Here are all parts of a method:

Modifier: modifier, which is optional and tells the compiler how to call the method. Defines the access type of the method.

Return value type: the method may return a value. Returnvaluetype is the data type of the return value of the method. Some methods perform the desired operation but do not return a value. In this case, returnvaluetype is the keyword void

Method name: is the actual name of the method. The method name and parameter list together constitute the method signature.

Parameter list: the parameter is like a placeholder. When called, the value is passed to the parameter. This value is called an argument or variable. Parameter list refers to the parameter type, order and number of parameters of a method. Parameters are optional, and methods can contain no parameters.

     Formal parameters: used to accept external input data when a method is called.

     Actual parameters: the data actually passed to the method when the method is called.

Method body: the method contains specific statements that define the method.

[construct a method to sum two numbers]

    public static int jia(int x ,int y){
        return x+y;

The formal parameters are x and Y in parentheses (that is, the values in parentheses after the method name when defining the method)

The actual parameters are x and Y outside parentheses

Method call

What is a method call?

Method call, more commonly, is to call this method in other places

How do I call a method?

Object name Method name (argument list)

Java supports two methods of calling methods, which are selected according to whether the method returns a value.

When a method returns a value, the method call is usually treated as a value. For example:

int larger =max(30,40);

If the return value of the method is void, the method call must be a statement.

System.out.println("Hello,kuangshen!")

Common interview questions: Value Passing and reference passing

Call a method that is smaller than:

Java from entry to factory method definition, call overload to pass parameters

 0

Method overload

What is method overloading

Overloading is a function with the same function name but different formal parameters in a class.

[thinking] the code above compares the sizes of two integers. What if I want to compare the sizes of two double classes?

Then you need to use method overloading!

public static double max(double num1, double num2) {
 if (num1 > num2) return num1;
 else
return num2; 
}
public static int max(int num1, int num2) {
 int result;
 if (num1 > num2)
 result = num1;
 else
 result = num2;
 return result; 
}

Therefore, to sum up, the case where the method name is the same but the parameter list is different is the overloading of the method!

Rules for overloaded methods:

Method names must be the same. (if the name is different, it is either overloaded or different methods)

The parameter list must be different (different number, different type, different order of parameter list, etc.)

The return type of the method can be the same or different.

Just different return types are not enough to overload methods

Implementation theory:

If the method names are the same, the compiler will call the method one by one according to the number of parameters, parameter types, etcmatching, the corresponding method has been selected. If the matching fails, the compiler will report an error.

Later learning source code will be used!

Recursive call:

What is recursion?

It’s easy for us to understand that method a calls method B! Recursion is also similar to it. Recursion is: method a calls method a, that is, it calls itself!

What are the benefits of recursion?

Using recursion, we can solve some complex problems with simple programs. Usually, a large-scale problem is transformed into a small-scale problem similar to the original problem layer by layer. The recursive strategy only needs a small number of programs to describe the multiple repeated calculations required in the problem-solving process, which greatly reduces the amount of code of the program. The ability of recursion is to define an infinite set of objects with specified statements

The recursive structure consists of two parts:

Recursive header: when not to call its own method. If there is no head, it will fall into a dead circle!

Recursive body: when to call its own method. The factorial of 5 is solved recursively:

public static void main(String[]args){
System.out.println(f(n=5)) 
}
public static int f(int n){

if(n==1){

return 1;
}else{
return n*f(n-1);
}
}
}

code analysis: if n= 1, it will return n * f (n-1). At this time, it will continue to execute f (n-1) from the beginning to realize recursive call//in other words: when n = 5, the main function will call f (5), then f (4), and then f (3) Stop calling until n = 1, and then return the value (return), as shown in the figure:

                    Java from entry to factory method definition, call overload to pass parameters

Analyze according to three conditions of recursion:
(1) Boundary condition: factorial. When it is multiplied to the last number, i.e. 1, it returns 1, and the program is executed to the end;
(2) Stage before recursion: when the current parameter is not equal to 1, continue to call itself;
(3) Recursive return stage: multiply from the maximum number. If the current parameter is 5, it is 5 4, that is, 5 (5-1), that is, n * (n-1)
                                                                                                                                                 

be careful: do not use recursion when the depth of the algorithm is relatively large. For example, if you calculate the factorial of 100 above, the computer may get stuck, because the Java stack cannot be compressed so much! So recursion is not recommended!

Why is recursion not recommendedRecursion: to put it bluntly, it is a kind of thought learning, that is, recursive thought. Small algorithms can be used, large algorithms can’t! Because it is not a particularly excellent algorithm.                                                                  

Homework after class

                                                                                                              

Job:
Write a calculator, which is required to realize the function of addition, subtraction, multiplication and division, and can receive new data circularly, which can be realized through user interaction. Recommended ideas:
1. Write four methods: addition, subtraction, multiplication and division
2. Use loop + switch for user interaction
3. Pass two numbers to be operated
4. Output results
I wrote it myself as follows:

I don’t think it’s perfect. Please give me more suggestions!!

package demo;

import java.util.Scanner;

public class jianjianchengchu {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System. out. Println ("1. Addition");
        System. out. Println ("2. Subtraction");
        System. out. Println ("3. Multiplication");
        System. out. Println ("4. Division");
        System. out. Println ("please enter two numbers:");
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        System. out. Println ("please enter the algorithm you want to use:");
        int c=scanner.nextInt();
        switch (c) {
            case 1:
                System. out. Println ("the result is:" + Jiafa (a, b));
                break;
            case 2:
                System. out. Println ("the result is:" + Jianfa (a, b));
                break;
            case 3:
                System. out. Println ("the result is:" + Chengfa (a, b));
                break;
            case 4:
                System. out. Println ("the result is:" + chufa (a, b));
                break;
            default:
                break;

        }
    }


        public static int jiafa(int x,int y)
        {
            return x+y;
        }
        public static int jianfa(int x, int y){

            return x-y;
        }

        public static int chengfa(int x,int y)
        {
            return x*y;
        }


        public static int chufa(int x, int y)
        {
            return x/y;
        }
}

Let’s have a light transport

Java from entry to factory method definition, call overload to pass parameters

Thank you. I hope the above articles will help you! Special thanks!