Static keyword: static

1. Static keyword: static

(1). The function of static Modifies the use of member variables

  1. Function of static keyword
  • Static means static and can modify member variables and member methods
  • static modifies a member variable, which means that only one copy of the member variable is stored in memory and can be shared and accessed Modification
    for instance:
package top.xiaoytongxue.day02;

public class User {
    //This onlineNumber is the member variable 
    public static int onlineNumber = 162;
    
    private String name;
    private int age;
    
    
}

2. Member variables can be divided into two categories

  • Static member variable (decorated with static, belonging to class, loaded once in memory): often represents information such as online number of people And other information that needs to be shared can be shared and accessed
public class User{
   //Static member variable
   public static String onlineNumber = 161;
}
Class name.Static member variable.(recommend)
object.Static member variable.(Not recommended)

public class User{
  public static String onlineNumber = 161;
  //Instance member variable
  object.Instance member variable (This can call instance member variables)
  private String name;
  private int age; 
}

Summary:
1. What are the classification and access of member variables?

  • Static member variable (decorated with static, belonging to class, loaded once and can be shared and accessed), access format:
    Class name Static member variables (recommended)
    Object Instance member variable (not recommended)
    2. Under what circumstances are two member variables defined?
  • Static member variable: indicates the number of online people and other information that needs to be shared
  • Instance member variable: belongs to each object with different information (name,age,...)

(2). Memory principle of static modified member variable

First, load the user in the method area Class, and then load the main method in the stack memory. In the stack memory, the addresses of User u1 and User u2 point to the heap memory, and small y and small h only point to a static variable area of static class

package top.xiaoytongxue.day02;

public class User {
    //Static member variable: it is decorated with static and belongs to a class. It is loaded once and can be shared and accessed
    public static int onlineNumber = 162;
    // Instance member variable: no static modification, belonging to each object
    private String name;
    private int age;

    public static void main(String[] args) {
        // 1. Class name Static member variable
        System.out.println(User.onlineNumber);
        System.out.println(onlineNumber);
        User.onlineNumber++;

        //System.out.println(name);  Private instance member variables cannot be accessed directly
        // 2. Create user object: Instance member variable
        User u1 = new User();
        u1.name = "Small y";
        u1.age = 18;
        System.out.println(u1.name);
        System.out.println(u1.age);
        // Object name Static member variables (not recommended)
        u1.onlineNumber++;

        User u2 = new User();
        u2.name = "Small h";
        u2.age = 29;
        System.out.println(u2.name);
        System.out.println(u2.age);
        //Object name Static member variables (not recommended)
        u2.onlineNumber++;
        System.out.println(User.onlineNumber);


    }

}

(3). Basic usage of static modifier member method

1. Classification of membership methods:

  • Static member methods (decorated with static, belonging to class) are recommended to be accessed by class name or object
  • Instance member method (no static modification, belonging to object) can only trigger access with object

Usage scenario

  • If it represents the behavior of the object itself and the winning method needs to access instance members, the method must be declared as an instance method
  • If the method aims to perform a common function, it can be declared as a static method

summary
1. What are the classification and access of member methods?

  • Static member method (decorated with static, belonging to class and object sharing) access format:
    Class name Static member method
    Object Static member method (not recommended)
  • Access format of instance member method (no static decoration, belonging to object):
    Object Instance member method
    2. What are the usage scenarios for each member method?
  • If it represents the behavior of the object itself, and the method needs to access instance members, the method must be declared as an instance method
  • If the method is for the purpose of performing a general function or needs convenient access, it can be declared as a static method

Case: make a random verification code and use the static member method

package top.xiaoytongxue.day01;

import java.util.Random;

public class demo1 {
    public static void main(String[] args) {
          createCode(5);
    }

    /***
     * Here, the randomly generated verification code is made into a static method for easy calling
     * @param n
     * @return
     */
    public static String createCode(int n){
        //1. Use String to develop a verification code
        String chars = "abcdefgfijklmnopqrstuvwsyzABCDEFGHIJKLMNOPJRSTUVWSYZ0123456789";
        //2. Define a variable to store a five digit random character as the verification code
        String code = "";
        //3. Circulation
        Random r = new Random();
        for (int i = 0; i < n; i++) {
            int index = r.nextInt(chars.length());
            //4. Extract the corresponding characters according to the random index
            code += chars.charAt(index);
        }
        System.out.println("The random verification code is:" + code);
        return code;
    }

}

(4). Memory principle of static modified member method

(5). Practical application case of static: design tool class

1. What are tools?

  • The tool class defines some static methods, and each method aims to complete a common function
    For example, in an enterprise's management system, it is usually necessary to use verification codes in many businesses of a system for security control such as anti refresh The verification code solves this problem very well However, if verification code logic exists in many places such as login and registration, it will lead to multiple development of the same function, and the code repetition will be too high

Benefits of tools

  • First, it is convenient to call, and second, it improves code reuse (once written, available everywhere)
    Why do methods in tool classes not use instance methods?
  • The instance method needs to create an object call. At this time, the object is only used to call the method, which will only waste memory
    Note on the definition of tool class
  • It is recommended that the constructor of the tool class be private, and the tool class does not need to create objects
  • There are static methods, which can be accessed directly by class name

summary
1. What are tools and what are their benefits?

  • There are some static methods inside, and each method completes a function
  • Once written, it can be used everywhere to improve the reusability of code
    2. What are the requirements for tools?
  • It is recommended to privatize the constructor of the tool class
  • Tool classes do not need to create objects

case

    /*
    Static method
    */
    public static double getAverage(int[] arr){
        // Evaluate max min
        int max = arr[0];
        int min = arr[0];
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > max){
                max = arr[i];
            }
            if (arr[i] < min){
                min = arr[i];
            }
            sum += arr[i];
        }
        return sum;
    }







    /*
    Static method
     */

    public static String toString(int[] arr){
        if (arr != null){
            String result = "[";
            for (int i = 0; i < arr.length; i++) {
                result += (i == arr.length - 1 ? arr[i] : arr[i] + ",");
            }
            result += "]";
            return result;
        }else {
            return null;
        }
    }
}

(6). Summary of static precautions [interview hot spots]

Implementation of static access:

  • Static methods can only access static members, not instance members directly
  • Instance methods can access static members or instance members
  • this keyword cannot appear in static methods
package top.xiaoytongxue.day02;

public class demo2 {
    //Static member variable
    public static int onlineNumber;
    //Instance member variable
    private String name;
    
    public static void getMax(){
        // 1. Static methods can directly access static members
        System.out.println(demo2.onlineNumber);
        System.out.println(onlineNumber);
        inAddr();
        
        //3. this keyword cannot appear in static methods
        System.out.println(this);
    }

    private static void inAddr() {
    }
    
    public void run(){
        //2. Instance methods can directly access static members or instance members
        System.out.println(demo2.onlineNumber);
        System.out.println(onlineNumber);
        demo2.getMax();
        getMax();

        System.out.println(name);
        sing();
    }

    private void sing() {
    }
}

2.static application knowledge: code block

3.static application knowledge: single example

4. The second of the three characteristics of object-oriented: inheritance

Added by Dan400007 on Sun, 23 Jan 2022 04:55:09 +0200