专家们好:
以下我随便定义一个类/*************************
class A{ static int a = 1; //1
static int b static{ //2
b =1
}}请问一下,1跟2两种定义方法有什么主要区别? (我自己感觉好像一模一样,呵呵)
以下我随便定义一个类/*************************
class A{ static int a = 1; //1
static int b static{ //2
b =1
}}请问一下,1跟2两种定义方法有什么主要区别? (我自己感觉好像一模一样,呵呵)
public class Object { private static native void registerNatives();
static {
registerNatives();
}
........
是按照出现顺序来执行的
测试:
public class Test { public static void main(String[] args) {
}
public static int b;
static {
b = 11;
}
public static int a = 1; public static void test() {
System.out.println("hello");
}
static {
test();
}
public static int c = 3;
}
bytecode:Compiled from "Test.java"
public class Test extends java.lang.Object{
public static int b;public static int a;public static int c;public Test();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: returnpublic static void main(java.lang.String[]);
Code:
0: returnpublic static void test();
Code:
0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #3; //String hello
5: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: returnstatic {};
Code:
0: bipush 11
2: putstatic #5; //Field b:I
5: iconst_1
6: putstatic #6; //Field a:I
9: invokestatic #7; //Method test:()V
12: iconst_3
13: putstatic #8; //Field c:I
16: return}看看static{}
这个我这样来解释下:
类的link分三个阶段:verification, preparation,and Resolution(在preparation阶段会跟据变量的类型配“默认值”如:int为0,其原因是在preparation阶段要为变量分配内存,内存里总要放东西吧?放什么好呢?就是...默认值)
link之后才有Initialization(这个阶段才是楼上朋友编译后代码中可以看到的程序本身逻辑上的执行,也就是给内存改值)所以说
“But here is a problem: if the static block try to evaluate a variable and the variable is not defined before this block. Is it a compiler error?”
这个问题不会出现
Does it mean that in a class variables are firstly initialized? I don't know the exact mechannism...