Use of static in Java

Reprinted from https://www.cnblogs.com/dolphin0520/p/10651845.html

Author Matrix Haizi

This article is a note

0. General

static can be used to modify methods, member variables, or code blocks.

The biggest advantage of static is that you can directly use static modified methods or variables without creating objects.

1. static modification method

Methods modified by static are called static methods. The biggest difference between static methods and ordinary methods is that static methods do not have this. This explains why non static member variables and methods of a class cannot be accessed in static methods, because non static member variables and methods depend on specific objects, while static methods do not have this, let alone access things in objects.

However, it should be noted that static member methods and variables can be accessed in non static methods.

Suppose there is a piece of code at this time

class Student {
    private String name = "Cayman";
    private static String s_name = "static Cayman";

    public Student() {
    }

    //This code is correct
    public void printName() {
        System.out.println(name);
        System.out.println(s_name);
        printStaticName();
    }

    
    public static void printStaticName() {
        System.out.println(name);
        //Non static member methods cannot be accessed in static methods
        System.out.println(s_name);
        //Non static member variables cannot be accessed in static methods
        printName();
    }

    private static void main(String[] args){
        Student s = new Student();
        //The following line will report an error because there is no object at this time, let alone accessing the member variable name
        Student.printStaticName();
    }
}

In the final analysis, the fundamental reason why non static member variables and methods cannot be used in static methods is that there is no specific object for it to access non static member variables and methods when calling static methods.

For non static member methods, of course, you can access static methods that are independent of objects.

Therefore, as long as we find that a method can be used without creating an object during coding, we need to declare this method as static. This is why the main method needs to be declared as static, because there is no specific object when the program runs the main method.

2. static modifies member variables

Variables modified by static are called static variables. The difference between static variables and non static variables is

  • A static variable is a variable from the perspective of a class, while a non static variable is a variable from the perspective of an object, that is, there is only one copy of the static variable declared in a class, which is called by all objects of the class, and the non static variable has its own copy for each specific object, which does not affect each other.

  • Static variables are initialized when the class is loaded, and will only be initialized once!

  • The static variable is located in the method area; Normal member variables are located in the heap.

  • The life cycle of static variable is the same as that of class; A normal member variable has the same life cycle as the object to which it belongs.

  • When an object is serialized (Serializable), static variables are excluded (because static variables belong to classes, not objects)

There are several common usage scenarios for static variables

  • Use variables without creating objects

  • As a shared variable, such as a counter

  • Singleton mode

3. static modifier code block

In the Java language, a piece of code enclosed by curly brackets {} is a code block, and static can be directly used to modify a code block, such as

class Student() {
    static {
        System.out.println("Hello!")
    }
    // field
    ...
    // constructor
    ...
    //method
    ...
}

At this point, the Student class will output the Hello string when it is first loaded and only when it is first loaded. And static code blocks can be placed anywhere in the program.

static code blocks can often improve the efficiency of code, so they are used to implement those code segments that need to be completed only once in the running of the program.

4. static can also guide packets statically

for example

// If static is not added, an error will be reported
import static java.lang.Math.random()

5. Some precautions for static

  1. static does not change the access permission of the domain or method. In Java, the only keywords that can affect the access permission are private, public and protected.

  2. static does not allow you to modify local variables.

6. Code analysis with static

public class Main {  
    static int value = 33;
 
    public static void main(String[] args) throws Exception{
        new Main().printValue();
    }
 
    private void printValue(){
        int value = 3;
        System.out.println(this.value);
    }
// 33
}

Use this in printValue Value actually accesses the static variable value in the main class. This is because in Java, this keyword refers to the reference of the current object and has nothing to do with the local object. In the main function, a main object has been generated after new Main(), This object has the value field (each main object has this field and points to the same place).

public class Test extends Base{
    static{
        System.out.println("test static");
    }
     
    public Test(){
        System.out.println("test constructor");
    }
     
    public static void main(String[] args) {
        new Test();
    }
}
 
class Base{
    static{
        System.out.println("base static");
    }
     
    public Base(){
        System.out.println("base constructor");
    }
}
/*
    base static
    test static
    base constructor
    test constructor
*/

As you can see from the above code, Test class is a subclass of Base. Therefore, before the program runs, the parent class is loaded first, so the Base class is loaded to run the static block, and then the Test class is loaded to run the static block. After entering the main method, the constructor of the parent class will be called first, and then the constructor of the child class Test will be called.

//1. Load the Test class and enter test static
public class Test {
    //5. Initialize the member variable of the parent class of Myclass and load the Person class
    Person person = new Person("Test");
    static{
        System.out.println("test static");
    }
    //8. After initializing the person field, start to construct the Test object and output the test constructor
    public Test() {
        System.out.println("test constructor");
    }
     
    public static void main(String[] args) {
        //2. Try to create a new Myclass object. At this time, load the Myclass class
        new MyClass();
    }
}
//6. Load the Person class, output the static block, initialize the Person object and complete the construction
class Person{
    static{
        System.out.println("person static");
    }
    //7. After initialization, output person test
    public Person(String str) {
        System.out.println("person "+str);
    }
}
//3. Load the Myclass class. If it is found to be a subclass of Test, load Test first, but Test has already been loaded, so directly enter the class and output myclass static,
//4. After loading, start to generate objects through the constructor, but first initialize the member variables of the parent class
class MyClass extends Test {
//9. After initializing the parent class, start initializing the member variables of the child class, enter the Person constructor again, and output person MyClass
    Person person = new Person("MyClass");
    static{
        System.out.println("myclass static");
    }
    //10. Construct MyClass object through constructor and output myclass constructor
    public MyClass() {
        System.out.println("myclass constructor");
    }
}
/*
    test static
    myclass static
    person static
    person Test
    test constructor
    person MyClass
    myclass constructor
*/

Added by HairyScotsman on Wed, 09 Mar 2022 18:22:04 +0200