Write in front: the blogger is a real combat development after training into the cause of the “hill pig”, nickname from the cartoon “Lion King” in “Peng Peng”, always optimistic, positive attitude towards things around. My technical path from Java full stack engineer all the way to big data development, data mining field, now there are small achievements, I would like to share with you what I have learned in the past, I hope to help you on the way of learning. At the same time, the blogger also wants to build a perfect technical library through this attempt. Any anomalies, errors and matters needing attention related to the technical points of the article will be listed at the end, and everyone is welcome to provide materials in various ways.

  • Please criticize any mistakes in the article and revise them in time.
  • If you have any questions you would like to discuss or learn, please contact me at [email protected].
  • The style of the published article varies from column to column, and all are self-contained. Please correct the deficiencies.

Java program method design

Keywords: Java, method definition, method design, method call, method overload \

The article directories

I. Definition of methods

The first program we came into contact with after learning Java programming is “Hello World “, which involves two main structures: class and main method. At that time, we just explained that main method is the entrance to the program, so when we want to define a method ourselves, how should we start?

1. Concept and function

First of all, we should clarify the concept and function of methods. In terms of name, methods can also be called functions, which are used to solve the same kind of problems. In terms of code structure, defining methods can reduce code duplication and make the overall program structure cleaner.

  • Let’s say we need to add two numbers
public class Test{
    public static void main(String[] args){
        // Define two variables, so easy
        int a = 10,b = 5;
        int c = a + b;
        System.out.println(c);/ / 15}}Copy the code
  • If we need to execute the same logic over and over again, we’ll end up with a lot of the same code
public class Test{
    public static void main(String[] args){
        int a = 10,b = 5;
        int c = 20,d = 10;
        // You can see that although the variable names are different, the calculation logic is the same
        // If a certain piece of code appears repeatedly, we can consider extracting it as a method
        int e = a + b;
        System.out.println(e);/ / 15
        int f = c + d;
        System.out.println(f);/ / 30
        int g = e + f;
        System.out.println(g);/ / 45}}Copy the code
  • After the method is defined
public class Test{
    public static void main(String[] args){
        int a = 10,b = 5;
        int c = 20,d = 10;
        // The original code logic will be converted to method calls
        plus(a,b);// Output when executing the method: 15
        plus(c,d);// Output when executing the method: 30
        plus(e,f);// Output when executing the method: 45
    }
    // Define a method that computes the sum of two numbers and outputs the result
    public static void plus(int m,int n){
        intresult = m + n; System.out.println(result); }}Copy the code

From the above examples, we can see:

  • Structurally, a method is a collection of lines of code
  • From a usage point of view, the purpose of defining methods is to extract common parts and reduce the occurrence of duplicate code
  • In the end, execution of multiple lines of code translates into method calls

2. Defined format

If we want to define a method, we need to first understand the structure of the definition method, in order:

  • Modifiers: Qualify methods in a manner that precedes the return value type

    • Permission modifiers: Usually we write permission modifiers at the beginning of the method definition. It specifies where the method can be called
    • Other modifiers: Keywords that can modify methods include static, final, etc., which will be described in other articles. There is no strict order for modifiers
  • Return value type: Indicates whether a method should be returned after execution, and the corresponding type

  • Method name: Specifies the name of the method to be used when the method is called. Methods with the same name in the same class constitute an overload

  • Argument list: Declares the arguments that need to be passed in when a method is called. They can be empty or multiple

  • Method body: The code executed when a method is called, which is the core part of the method and needs to correspond to the method return value type

3. Method signature

The method name and parameter list form the method signature, which uniquely identifies a method and is useful for identifying whether it constitutes an overload.

public class Test{
    Method signature: main(String[] args)
    public static void main(String[] args){
        int a = 10,b = 5;
        int c = plus(a,b);
    }
    Plus (int m,int n)
    public static int plus(int m,int n){
        returnm + n; }}Copy the code

4. Method comments

After defining a method, we can only see the method signature and return value type when we use the compiler to call it. We hope to further describe similar or overloaded methods to help users distinguish methods. When you add comments to a method, you need to use document comments, called Javadoc, so that the information about the method can be displayed during the call. The comments for the method mainly include the following parts:

  • Function description: Describes the function of the method
  • Method parameter description: @param, explain the meaning of each parameter
  • Return type: @return, which explains the meaning of the returned value

The compiler can quickly generate a template for a method by typing /** :

public class Test{
    /** * computes the sum of two numbers *@paramA the first addend star@paramB The second addend star@returnThe sum of two numbers */
    public int plus(int a,int b){
        returna + b; }}Copy the code

Second, method design

After defining the structure of the method, what we need to do is to know how to define a method and have a clear idea when solving practical problems.

1. Ideas of method design

The author thinks that the design of a method is actually more like the epitome of the whole programming idea. Whether it is to complete a complex function or to define a method, the following three steps can be carried out:

  • What I want?

To define a method, it is necessary to define: what function do I need to accomplish, and what problem do I need to solve? Once we know what the method is for, we can then determine the name of the method, the return value type, the calling access rights, and whether there are any other modifiers.

  • What I need?

The next step is to consider what the method needs to be executed based on its purpose. Do we need to pass in some parameters? So we can determine the part of the argument list.

  • How to do?

Once we know what problem the method is trying to solve and what parameters it needs, we can analyze what code the method should write to solve the problem. That is, we can finally determine the part of the method body, use the parameters passed in, and finally return the variables that should be returned or print out.

2. Determination of method name

Method names are easier to define because there is a high degree of customization and no mandatory rules, as long as the identifiers are satisfied. Generally speaking, the method name should be known by name. It should start with a lowercase letter. If multiple words are uppercase, the method name can be a combination of letters and numbers.

3. Determine the parameter list

The determination of the parameter list is mainly to consider the type of the parameter that needs to be passed when calling the method. It can be empty, or one or more parameters. The type and name need to be declared respectively.

  • Declared types are used to restrict the types of arguments passed in when a method is called
  • The name of the declaration is used to represent the parameters passed in

In addition, we need to understand the differences between the various parameter types:

  • Basic data types: For basic data types, we can think of value passing, that is, it is a process of copying the value, if we change the value of the parameter in the method, the original value will not change.
public class Test{
    public static void main(String[] args){
        int a = 10;
        test(a);// call a method in which the value is modified
        System.out.println(a);// Result is 10
    }
    public static void test(int n){
        System.out.println(n);// The value is received and the result is 10
        n = 100;// Change the value of n without affecting the value of the passed parameter a
        System.out.println(n);// The result is 100}}Copy the code
  • Reference types, reference types, including arrays, which is in addition to basic data types of other types, what happened in the pass is reference, that is received is a reference parameters, the equivalent of more than a variable pointing to the same place, so that changes in the way will directly effect on the object instance.
public class Test{
    public static void main(String[] args){
        int[] a = {1.2.3};
        test(a);// call a method where array A is modified
        for(int i = 0; i < a.length; i++){ System.out.println(n);// the result is 10,20,30}}public static void test(int[] n){
        for(int i = 0; i < n.length; i++){ System.out.println(n[i]);// receives a reference to the array with the result :1,2,3
        }
        for(int i = 0; i < n.length; i++){ n[i] = n[i] *10;// Change the value of the array so that each element is 10 times the original value
        }
        // The same applies directly to the object itself}}Copy the code

  • Mutable arguments: Mutable arguments are similar to arrays but different, allowing arguments to be passed in as a list when called

    • A variable parameter is also called an indefinite parameter, which is used when I’m not sure how many arguments there are, but I don’t want to build an array every time
    • Only one variable parameter can appear in a method definition
    • A variable argument can only appear in the last position of the argument list
    • The use of the Object type as a variable parameter type is not recommended and will be explained when method overloading occurs
    • Declaration format: Parameter type… Parameter names, such as int… nums
public class Test{
    public static void main(String[] args){
        int a = 1;
        int b = 2;
        int c = 3;
        test(null);// The call succeeds, and the parameter is null
        test();// The call succeeds, and the number of arguments is 0
        test(a);// The call succeeds, passing in 1 argument
        test(a,b);// The call succeeds, passing in two arguments
        test(new int[]{a,b,c});// The call succeeds, or it can be constructed into an array and passed in
    }
    public static void test(int. nums){
        // Use nums as an array to determine the number of parameters to be passed
        // If the argument passed is not null, a null pointer exception will occur
        if(nums == null){
            System.out.println("The argument passed in is null");
        }else{
            System.out.println("The number of arguments passed in is :"+ nums.length); }}}Copy the code

4. Determination of return type

How do you determine if a method needs to have a return value? In all of the above methods, we use the void keyword in the return type part, which means that the method returns a value that is empty or does not need to return. In fact, whether or not a method needs to return is not a syntactic matter, but depends on the needs of our users. Let’s discuss both cases.

  • Void: no return value is required after the method is executed. That is, the return keyword is not required. Only the method logic needs to be completed, some information needs to be output, or some attributes of the object need to be modified by reference.

  • Other types of

    • Only one return value type can be specified, but it can be an array type
    • If a return value type is declared, it must be used in conjunction with the return keyword
    • A return should normally only appear on the last line of a method as the end of the method
    • In a selection structure, it may not appear on the last line, and you can terminate a method early if you want, but you must ensure that all cases of the selection structure have a return value
    • A return must be followed by the name of a variable or an expression. The type of the variable or expression must be the same as the type of the return value
    • If you need to return the value of more than one variable at a time, you can use arrays
    • If you need to return multiple types of variables at the same time, you can declare the return value type as: Object[]
public class Test{
    public static void main(String[] args){
        // We need to implement the following logic: calculate the sum of two numbers and print the result as 10 times
        int a = 1,b = 2;
        // After the method call, we must find a way to get the sum of the two numbers before proceeding
        int c = plus(a,b);
        // Receive the return result with a variable of the corresponding type (c), and proceed
        int result = c * 10;
        System.out.println(result);
    }
    public static int plus(int a,int b){
        returna + b; }}Copy the code

5. Determination of method content

It is a process of long-term training and exercise to be able to write the contents of the method body skillfully and quickly as required. Sometimes, it is not that we do not know how to use the structure of method, but that we do not have any ideas about the problems given. Here I will give you some advice, because no amount of examples can help you in a short time.

In fact, the program itself is just an expression of our logical thinking, and the computer is really stupid, all the steps need you to tell him step by step, for example, if you want to write a program to judge prime numbers, do not expect you to define a variable I, and then use the selection structure to write in the judgment conditions: If (I == prime){} the computer will understand. You first have to teach the computer what a prime number is, or what conditions a number meets to be prime. Basically all problems can be transformed into a mathematical problem, or a logical problem with steps, especially when we want the computer to help us to complete an operation or function, you must tell it the specific steps, and how to deal with various situations, after all, the big guy said:



A: What do you think of this sentence?I don’t believe you! You’re a bad motherfucker. But it makes sense, especially for beginners, to try to understand how a computer works and how to teach it to help us solve problems.

The author’s suggestions can be summarized as follows:

  • Don’t rush into writing a method
  • First clarify the steps to solve the problem
  • If possible, break down each step, analyze possible situations, and propose solutions
  • Translate each step into the appropriate structure or code based on the grammar knowledge you have learned
  • If the problem is not resolved, repeat the above steps
  • After going through these steps a few times, you will be able to complete them completely in your head and write the method out smoothly

Method call

When a method is defined, it will only be executed if it is called, otherwise it makes no sense.

1. The format of method calls

Based on the above example, I think you already know how to call a method. Yes, it’s simple: method name + incoming parameter. Have written about parameters need to make a point, in the method definition, we need to declare the parameter type, and in a method is called, the incoming parameters, we need to do is match, don’t again parameter type, and only need to ensure that the incoming parameters match the type of the definition of good, can pass in a specific value, It can also be a variable that declares an assignment, but again, the type matches.

2. Method execution process

Method execution is relatively simple, and the structure of nested calls will be explained in a later article. The execution of a method uses a basic structure: the sequential structure. If a piece of code encounters a method call in the process of execution, it must enter the method, complete the execution of the code in the method, and then return to the method call, continue to execute the following code. Return = return; return = return; return = return; When did it come back? The explanation for this problem can be summed up in one sentence: return to the point where the method was called. First of all, only after a method is called does the code in it execute, and only then does the return statement execute. So where does the return go after that? In this case, the call statement of the whole method represents the return value of this method, and we can directly use the corresponding type of variables to receive it.

public class Test{
    public static void main(String[] args){
        // We need to implement the following logic: calculate the sum of two numbers and print the result as 10 times
        int a = 1,b = 2;// Code execution steps: 1
        // Execute step 2, perform method call
        int c = plus(a,b);// Execute step: 4, perform the return value assignment
        int result = c * 10;// Code execution step: 5
        System.out.println(result);// Code execution step: 6
    }
    public static int plus(int a,int b){
        return a + b;// Code execution step: 3}}Copy the code

3. Call precautions

  • The static modifier

The static modifier has many uses, and we’ll only discuss how it affects method calls when used on methods. Since the main method is the entry point to the program, it must be declared static, that is, executed without instantiating the object. Since the main method is static, the methods it calls directly must also be static.

  • Receive return value

Does a method with a return value have to receive the return value after it is called? Of course, it is not necessary; if it is not received, the value of the method is returned normally, but is then discarded. Receive the method call statement as a whole, directly with the corresponding type of variable assignment can receive. \

Method overloading

1. The concept of overloading

Overloading means that more than one method with the same name can be defined within a class, depending on the argument list. The concept of overloading is easy to understand, it just describes the phenomenon, in a class there are many methods with the same name, you need to understand how to define the rules of overloading, and what is the use of overloading?

  • The method names are the same, but the parameter lists are different

Don’t look at the concept is simple, there are still a lot of students overturned here. The same method name is easy to understand, exactly the same is called the same, case sensitive. Another concept is that parameter lists are different. It is important to note that parameter lists are the same or not, depending on the type and order of the parameters, not the parameter name. Because the parameter name declared in the parameter list is only a representation of the parameter passed in, there is no specific distinction.

public class Test{
    // The sum of two integers is plus
    public int plus(int a,int b){
        return a + b;
    }
    // The argument list is the same, does not constitute an overload, cannot exist in the class at the same time
    public int plus(int c,int d){
        return c + d;
    }
    // Different parameter lists constitute an overload
    public double plus(double a,double b){
        return a + b;
    }
    // Different parameter lists constitute overloads, but indefinite parameters can easily create ambiguity in the call, not recommended
    public int plus(int. a){
        return 0;
    }
    // The same argument list, different method name, does not constitute an overload, can exist in the class at the same time
    public int Plus(int a,int b){
        returna + b; }}Copy the code
  • What’s the use of method overloading?

Most of the time, we use methods to accomplish a function or logic. There are many cases, some cases from the code logic process, and some cases to do different operations for different parameter types. At this time, we can take advantage of the characteristics of overloading, using the same method name to represent the logic we need to deal with is similar, and then declare different parameter types in the parameter list, so that we can avoid complex writing in the method of various parameter number judgment, parameter type judgment, more conducive to maintenance. At the same time, using the same method type also makes it very convenient for users to call, there is no need to remember different method names on the same function, and at the same time, it can solve the problem well.

2. Overloaded method calls

For overloaded method calls, since the method names are the same, the JVM mainly distinguishes them based on the type of argument passed in, with the following effect:

public class Test{
    public static void main(String[] args){
        int a = 1,b = 2;
        int c = plus(a,b);Call plus(int a,int b)
        double m = 1.0,n = 2.0;
        double d = plus(m,n);// call plus(double a,double b)
    }
    // The sum of two integers is plus
    public static int plus(int a,int b){
        return a + b;
    }
    // The same method name but different argument lists constitute an overload
    public static double plus(double a,double b){
        returna + b; }}Copy the code

As you can see from the above example, the main distinguishing factor when performing a method call is the parameter type. However, it is important to note when an undefined parameter is present in a method:

public class Test{
    public static void main(String[] args){
        int a = 1,b = 2,c = 3;
        int d = plus(a);// Failed to compile with plus(int... A) and plus (int a, int... B) all match
        int e = plus(a,b);Call plus(int a,int b)
        int f = plus(a,b,c);// Failed to compile with plus(int... A) and plus (int a, int... B) all match
        int g = plus(new int[]{a,b});// Call plus(int... a)
        int h = plus(a,new int[]{b,c});// call plus(int a,int... b)
    }
    // The sum of two integers is plus
    public static int plus(int a,int b){
        return a + b;
    }
    // If the method name is the same, but the parameter list is different, it constitutes an overload. However, indefinite parameters can easily create ambiguity in the call, so it is not recommended
    public int plus(int. a){
        return 0;
    }
    // If the method name is the same, but the parameter list is different, it constitutes an overload. However, indefinite parameters can easily create ambiguity in the call, so it is not recommended
    public int plus(int a,int. b){
        return 0; }}Copy the code

From the above example, we can see if overloaded methods of uncertain parameters, then the call is likely to appear ambiguity, still need to be manually build array way to solve, so when making method overloading should try to avoid uncertain parameters, when the uncertain parameter is Object type, ambiguity problem will be more serious.