for instance:public class StaticInitDemo {static int i = 5;
static {
System.out.println("Static code i= "+ i++ );
}
}
public class Test {
public static void main(String args[]) {
System.out.println("Main code: i="
+ StaticInitDemo.i);
}
}将打印出:
Static code: i=5
Main code: i=6
static {
System.out.println("Static code i= "+ i++ );
}
}
public class Test {
public static void main(String args[]) {
System.out.println("Main code: i="
+ StaticInitDemo.i);
}
}将打印出:
Static code: i=5
Main code: i=6
public class A
{
static int a=9;
static {
a=4;
}
}
public class b
{
A s=new A();
System.out,println(a);
]我认为会出错啊
1. static variables initialization.
2. static initializer block execution. (in the order of declaration, if multiple blocks found)
3. constructor header ( super or this – implicit or explicit )
4. instance variables initialization / instance initializer block(s) execution
5. rest of the code in the constructor
static {
a=4;
System.out.println(a);//加上这句
}
static int a=9;
}编译报错: illegal forward reference
那为什么a=4可以.....召唤达人。
这是因为
In all the initializers, forward referencing of variables is not allowed. Forward referencing of methods is allowed.