我们可以在不初始化对象的情况下访问类的静态成员吗 ?

问题描述 投票:0回答:1
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);
                           ^

但是当我在主块系统内部移动声明时,将引发错误。为什么呢?

java
1个回答
0
投票

您应使用Another.i而不是a.i访问静态变量。

a.i是有效的语法,如果a具有值,但是会造成混淆。如果访问a时未对其进行初始化,则编译器不允许使用。

两个片段之间的区别在于:

static Another a;

[a的默认值为null

同时(当a是局部变量时:]

Another a;

没有默认值。

© www.soinside.com 2019 - 2024. All rights reserved.