4
为什么我们不能通过未初始化的局部变量访问静态内容?
看下面的代码: class Foo{ public static int x = 1; } class Bar{ public static void main(String[] args) { Foo foo; System.out.println(foo.x); // Error: Variable 'foo' might not have been initialized } } 如您所见,尝试x通过未初始化的局部变量Foo foo;代码访问静态字段时会foo.x生成编译错误:Variable 'foo' might not have been initialized。 它可能看起来像这样的错误是有道理的,但直到我们意识到,访问static成员的JVM不实际使用的价值变量,但只有它的类型。 例如,我可以foo使用value进行初始化,null这将使我们能够x毫无问题地进行访问: Foo foo = null; System.out.println(foo.x); //compiles and at …