要知道你在哪里声明字段的一件事是,这些字段是按顺序初始化的;你不能写:static
public class DoesNotCompile
{
private static final int foo = 1 + bar; // ERROR: bar is not defined
private static final int bar = 1;
但是,在您的情况下,情况略有不同:
class Q26 {
// Declared first, but NOT first to be initialized...
public static Q26 q26 = new Q26();
public int ans;
// The honor befalls to this one, since it is declared `final`
private static final int var1 = 5;
private static int var2 = 7; // zero until initialized
public Q26() {
ans = var1 + var2;
}
}
未初始化的默认值为 0;由于您的实例是在 和 之前声明的,但因为首先初始化(因为它是 ),因此结果是您所看到的:是 5。int
Q26
var1
var2
var1
final
ans
与此代码等效的代码可以是:
class Q26 {
public static Q26 q26;
private static final int var1;
private static int var2;
static {
var1 = 5;
q26 = new Q26();
var2 = 7;
}
public int ans;
public Q26() {
ans = var1 + var2;
}
}
进一步说明:还有静态初始化块;顺序对这些也很重要。您不能执行以下操作:
public class DoesNotCompileEither
{
static {
foo = 3; // ERROR: what is foo?
}
private static final int foo;
如果将静态初始值设定项放在 的声明下面,则将编译:foo
public class ThisOneCompiles
{
private static final int foo; // declared
static {
foo = 3; // initialized
}