Java—static modifier and final keyword

Modified with the static modifier , which can be a variable, method, or code block

  • The static variables, methods, or code blocks in the class belong to the class, not to a specific object.
  • The static members of the class can be used directly with the name of the class without creating objects of the class.
  • Static variables or methods are also called class variables or class methods

User:

public class User {
    
    
    // 多个代码块执行是顺序执行, 代码块在创建对象之前由 JVM 自动调用
    {
    
    
        System.out.println("代码块1...");
    }

    {
    
    
        System.out.println("代码块2...");
    }

    // 在调用静态变量和静态方法之前由JVM自动调用,顺序调用
    static {
    
    
        System.out.println("静态代码块1...");
    }

    static {
    
    
        System.out.println("静态代码块2...");
    }
	// 静态变量、类变量
    static String WORD = "静态变量word...";
	// 静态方法、类方法
    public static void show() {
    
    
        System.out.println("静态方法show()...");
    }
	//成员方法
    public void eat() {
    
    
        System.out.println("成员方法eat()...");
    }
	//构造方法
    public User() {
    
    
        System.out.println("构造方法...");
    }
}

Test:

public class Test {
    
    
    public static void main(String[] args) {
    
    
        new User();
    }
}

result:

静态代码块1...
静态代码块2...
代码块1...
代码块2...
构造方法...

If Test is:

public class Test {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(User.WORD);
        User.show();
    }
}

The result is:

静态代码块1...
静态代码块2...
静态变量word...
静态方法show()...

Execution order

  • Static code block -> code block -> constructor
  1. When the class is loaded, the JVM will initialize all static modified attributes, methods, and code blocks (automatically executed in sequence)
  2. Before calling the constructor, the JVM will initialize all member attributes, methods, and code blocks (automatically executed in sequence)

Due to the initialization sequence: static variables and static methods can only be accessed in static methods


final keyword

public final static String SURNAME="CAO";

The final modifier can be applied to classes, methods, and variables .

  • The meaning of final when applied to classes, methods and variables is different, but the essence is the same: final means immutable .
  • Classes declared as final cannot be inherited .
  • The declared method cannot be overridden . If a class is a final class, then all its methods are implicitly final;
  • The declared variable must be assigned an initial value . It is essentially a constant ;
  • Common final class: String System packaging class (Integer, Short, Byte, Long...)

Guess you like

Origin blog.csdn.net/qq_44371305/article/details/113354332