起因:代码里a=2前不加int,声明在后面,不懂为啥
public class TestStatic{
static {a=2;}
static int a=1;
static int b=3;
static {b=4;}
public static void main(String[] args){
System.out.println(a);
System.out.println(b);}
}
}
去stackoverflow提问后总结大佬们的回答:
1.局部变量是在赋值前必须先声明,代码里a不是局部变量,a是类变量
局部变量的作用域是声明了这个变量到block的最后。而不管静态还是非静态的字段(feilds)都是成员,作用域是整个类:
The scope of a declaration of a member
mdeclared in or inherited by a class or interface C (§8.2, §9.2) is the entire body ofC, including any nested class or interface declarations. IfCis a record class, then the scope of m additionally includes the header of the record declaration ofC.
a的作用域是整个testStatic,所以声明前也能用,和在函数定义前调用函数是一个道理
void f() {
g(); // can call g here!
}
void g() {}
但以下情况会报错:
class Foo {
static int b = a; // changing this to Foo.a works
static int a = 0;
}
因为:给类变量赋值的引用出现以下情况会报错:1.引用是类变量的初始化或是在类的静态初始化程序(静态代码块)里。2.。。。。不会翻译了我擦唉
References to a field are sometimes restricted, even through the field is in scope. The following rules constrain forward references to a field (where the use textually precedes the field declaration) as well as self-reference (where the field is used in its own initializer).
For a reference by simple name to a class variable f declared in class or interface C, it is a compile-time error if:
The reference appears either in a class variable initializer of C or in a static initializer of C (§8.7); and
The reference appears either in the initializer of f's own declarator or at a point to the left of f's declarator; and
The reference is not on the left hand side of an assignment expression (§15.26); and
The innermost class or interface enclosing the reference is C.
参见8.3.3章节的文档Chapter 8. Classes (oracle.com)
文章讨论了Java中类变量的声明与使用规则。在代码示例中,虽然`a=2`在声明之前,但由于`a`是类变量,其作用域覆盖整个类,所以在静态初始化块中可以使用。然而,对于类变量的引用,如果在声明前使用并出现在类或静态初始化块中,且未在赋值的左侧,会导致编译错误。文章还提到了静态块的执行顺序和继承时的影响。

1284

被折叠的 条评论
为什么被折叠?



