执行顺序,静态块,字段

onl*_*man 0 java static block

我知道静态块在任何事情之前运行.但是在这里,当调用B.test()时会发生什么?执行顺序和值的设定?后来,当b1设置为null时,b1.i如何计算为20?

class  B
{    
     static int i;
     static {
         i = 20;
         System.out.println("SIB");
     }
     static int test() {  
         int i = 24;
         System.out.println(i);
         return i; 
     }
}

public class Manager {
    public static void main(String[] arg) {
         B.test();
         B b1 = null;
         System.out.println(b1.i);  
    }
}
Run Code Online (Sandbox Code Playgroud)

输出是:

SIB
24
20
Run Code Online (Sandbox Code Playgroud)

tal*_*las 5

i这里的价值

static int i;
static {
    i = 20;
    System.out.println("SIB");
}
Run Code Online (Sandbox Code Playgroud)

设置为20并且从未修改,因此当您访问时b1.i,它仍然是20.

在您的test()方法中,您使用的另一个i变量与静态变量无关.