[Java | Basics] Detailed explanation of static keywords and code blocks

1 Introduction

This article mainly explains staticthe execution order of keywords and code blocks and the function of each part of code blocks.

2. static keyword

Keywords in Java staticare used to modify class members (static members), and can be used to modify static variables, static methods and static code blocks.

2.1 Static modification of member variables

Let's look at this code first:

public class Student {
    
    
    public String id;
    public String name;
    // static 修饰的成员变量
    public static String major = "软件工程";
    public Student(String id, String name) {
    
    
        this.id = id;
        this.name = name;
   }
}

insert image description here
Static modified member variables have three characteristics:

  1. Static members belong to the class , not to the instance, so they can be accessed directly by the class name.
  2. Static members are initialized when the class is loaded without creating an instance of the class.
  3. Static members are shared by all instances and can be used to store class-level information.

To put it simply, although the staticmodified , it is not recommended to use it. staticThe modified member variable also becomes a class member. It is recommended to use 类名.the method of access. 类名.The method of access also shows the static modification The member variables of the class are initialized when the class is loaded, and there is no need to create an instance of the class. Both student1 and student2 have the major member variable, indicating that the static member is shared by all instances.

Summary: staticVariables modified with keywords are called static variables, also called class variables. Static variables belong to the class, not to the instance. The value of a static variable is shared by all class instances and can be accessed directly through the class name. Static variables can be accessed in any method of the class without creating an instance of the class.

2.2 static modification member method

1. Static methods can only access static members
insert image description here
In the figure, we can see that the name is not modified by static, so an error is reported in the method func modified by static.

2. Static member methods can only access static member methods.
insert image description here
As can be seen from the figure, an error is reported when calling func3 method in func. Therefore, static member methods can only access static member methods.
3. Static member methods belong to classes.
insert image description here
Static methods belong to classes. Therefore, it can also 类名.be accessed by means of

In fact, there is another point. Static methods cannot be rewritten and cannot be used to achieve polymorphism. This will be explained in polymorphism.

Summary : staticMethods modified with keywords are called static methods, also known as class methods. Static methods belong to the class, not to the instance. Static methods can be accessed directly through the class name without creating an instance of the class. Static methods can only access static variables or call other static methods.

3. Code blocks

A code block is a piece of code surrounded by curly braces, used to organize code and limit the scope of variables

3.1 Common code blocks

Ordinary method blocks use {}definitions directly
Example:

    public static void main(String[] args) {
    
    
        {
    
    
            int x = 20;
            System.out.println(x);
        }
        int x = 10;
        System.out.println(x);
    }
    // 输出结果:
    // 20
	// 10

This kind of usage is rare, just understand

3.2 Static code blocks

A code block defined using static is called a static code block. Generally used to initialize static member variables

public class Student {
    
    
    public String id;
    public String name;
    public static String major;

    static {
    
    
        major = "软件工程";
        System.out.println("执行了 静态代码块");
    }
}

insert image description here
No matter how many objects are generated in the static code block, it will only be executed once

3.3 Constructing code blocks

Building block: A block of code defined in a class (without modifiers). Also called example code block. Construction code blocks are generally used to initialize instance member variables.
Example:
Student class

public class Student {
    
    
    public String id;
    public String name;

    {
    
    
        this.id = "1";
        this.name = "张三";
    }

    @Override
    public String toString() {
    
    
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}
    public static void main(String[] args) {
    
    
        Student student = new Student();
        System.out.println(student.toString());
    }

operation result:
insert image description here

Precautions when using code blocks:

  1. No matter how many objects are generated in the static code block, it will only be executed once
  2. If a class contains multiple static code blocks, when compiling the code, the compiler will merge them in order of definition
  3. The instance code block will only be executed when the object is created

Take a look at the execution order of the code blocks:

public class Demo {
    
    
    private static int x = 1;
    private int y = 2;

    static {
    
    
        System.out.println("静态代码块1,x=" + x);
        x = 10;
    }

    {
    
    
        System.out.println("实例代码块1,x=" + x + ", y=" + y);
        y = 20;
    }

    public Demo() {
    
    
        System.out.println("构造函数,x=" + x + ", y=" + y);
        y = 30;
    }

    static {
    
    
        System.out.println("静态代码块2,x=" + x);
        x = 100;
    }

    {
    
    
        System.out.println("实例代码块2,x=" + x + ", y=" + y);
        y = 40;
    }
    public static void main(String[] args) {
    
    
        Demo demo1 = new Demo();
        Demo demo2 = new Demo();
    }
}

insert image description here
The order of execution of the code blocks:

  1. Execute the static one first (it will be executed when the class is loaded), and it will only be executed once. If there are multiple static code blocks, see the order of definition
  2. Secondly, execute the example code block, if there are more than one, look at the order of definition
  3. constructor execution

4. Summary

staticKeywords can be used to define class-level variables, methods, and code blocks, and directly access static member variables and static member methods through class names. The execution order of code blocks and the role of each part of code blocks are also important.

Thank you for watching! I hope this article can help you!
Column: "Java Learning Journey from Scratch" is constantly being updated, welcome to subscribe!
"Wish to encourage you and work together!"
insert image description here

Guess you like

Origin blog.csdn.net/m0_63463510/article/details/129199249