public class Test{
static Another a;// without initializing i can able to access static member of Another class
public static void main(String[] args){
System.out.println(a.i);
}
}
class Another{
public static int i=20;
}
这里我可以成为类Another的静态成员,而无需初始化对象
public class Test{
public static void main(String[] args){
Another a;// but when i declare this inside the main method system is throwing error
System.out.println(a.i);
}
}
class Another{
public static int i=20;
}
Test.java:5: error: variable a might not have been initialized
System.out.println(a.i);
^
但是当我在主块系统内部移动声明时,将引发错误。为什么呢?
您应使用Another.i
而不是a.i
访问静态变量。
a.i
是有效的语法,如果a
具有值,但是会造成混淆。如果访问a
时未对其进行初始化,则编译器不允许使用。
两个片段之间的区别在于:
static Another a;
[a
的默认值为null
。
同时(当a
是局部变量时:]
Another a;
没有默认值。