Execution order of the static variables, static code block, static methods

package Day_1_11;

/**
 * @author 郑悦恺
 * @Classname Test
 * @Description TODO
 * @Date 2020/1/11 14:20
 */

class A{
    static int i=0;
    static {
        System.out.println("静态代码块A");
    }
    public A(){
        System.out.println("构造方法A");
    }

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

    static {
        i++;
        System.out.println("在类A中静态变量i="+i);
    }
}
public class B extends A{

    static {
        System.out.println("静态代码块B");
    }
    public B(){
        System.out.println("构造方法B");
    }
    {
        System.out.println("代码块B");
    }
    public static void main(String[] args) {
        System.out.println("main方法");
        new B();
        System.out.println("--------------------");
        new B();
    }

    static {
        i++;
        System.out.println("在类B中静态变量i="+i);
    }

}

Results of the

A static block of code
in the class A static variable i = 1
static code block B
in the static class variable B = 2 I
main method of
block A
constructor A
block B
Constructor B


A code block
constructor A
block B
Constructor B

Process finished with exit code 0

We can draw the following conclusions

  • Static variables are global
  • Static method is executed when the class is loaded, it will only be executed once
  • Static variables and static methods are executed in the order of declaration
  • Static constructor parent class> blocks static method subclass> the Main Functions> parent class> parent class constructor> subclass code blocks> subclass
Released eight original articles · won praise 1 · views 134

Guess you like

Origin blog.csdn.net/qq_41936422/article/details/103936271