请教static代码块初始顺序的问题。
代码1:
Java代码 复制代码
1. public class MyObject {
2.
3. public void getX(){
4. System.out.print("x =" + x);
5. }
6.
7. static int x = 10;
8.
9. static {
10. x = 20;
11. }
12.
13. public static void main(String [] args){
14. MyObject myObject = new MyObject();
15. myObject.getX();
16. }
17.
18. }
public class MyObject {
public void getX(){
System.out.print("x =" + x);
}
static int x = 10;
static {
x = 20;
}
public static void main(String [] args){
MyObject myObject = new MyObject();
myObject.getX();
}
}
此时打印结果是:
x = 20
貌似static块是按照顺序从上往下执行的。
但是
代码2
Java代码 复制代码
1. public class MyObject {
2.
3. public void getX(){
4. System.out.print("x =" + x);
5. }
6.
7. static {
8. x = 20;
9. }
10.
11. static int x = 10;
12.
13. public static void main(String [] args){
14. MyObject myObject = new MyObject();
15. myObject.getX();
16. }
17.
18. }
public class MyObject {
public void getX(){
System.out.print("x =" + x);
}
static {
x = 20;
}
static int x = 10;
public static void main(String [] args){
MyObject myObject = new MyObject();
myObject.getX();
}
}
编译通过,此时打印结果是:
x = 10
难道是说 x 先被初始化为0?
接着
代码3:
Java代码 复制代码
1. public class MyObject {
2.
3. public void getX(){
4. System.out.print("x =" + x);
5. }
6.
7. static {
8. System.out.println(x);
9. }
10.
11. static int x = 10;
12.
13. public static void main(String [] args){
14. MyObject myObject = new MyObject();
15. myObject.getX();
16. }
17.
18. }
public class MyObject {
public void getX(){
System.out.print("x =" + x);
}
static {
System.out.println(x);
}
static int x = 10;
public static void main(String [] args){
MyObject myObject = new MyObject();
myObject.getX();
}
}
如果是初始化为0.
那么为何此时编译不过。
出错位置:System.out.println(x);
------解决方案--------------------LZ别生气了,大家都挺热情的啊
1、都是静态的话,顺序从上而下.
2.初始化为0.
public class MyObject {
public void getX(){
System.out.print("x =" + x);
}
static int x; //你没有定义哦,既然没定义,是不会初始为0的;类方法怎样我不清楚,但是static块确实是在main()方法
//之前执行的.
static {