本帖最后由 kerner 于 2014-11-27 09:37 编辑
第一问:
静态代码块是在类加载完后执行的,int默认初始化为0,然后是执行静态代码中的 System.out.println(StaticDemo.i);所以会输出0;
第二问:
静态代码块是在类加载完后执行的,int默认初始化为0,然后是执行静态代码中的 数值初始化为10,System.out.println(StaticDemo.i);所以会输出10;
第三问:
所有的变量在使用前都应该是先声明。不能向前引用,但是为什么第一个,第二个可以,第三个不可以呢?这个答案会帮助你。The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold: The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C. The usage is not on the left hand side of an assignment. The usage is via a simple name. C is the innermost class or interface enclosing the usage.
It is a compile-time error if any of the four requirements above are not met.
第三个,
i=10, i在赋值符号的左边,所以编译器不会报错。但是System.out.println(i),不满足上面四条,所以会报错,写成StaticDemo.i就不会报错。
|