java - 在 Java 中访问静态字段的正确方法是什么?

标签 java class variables static

我刚开始学习 Java,我写了一个类来测试使用静态字段。一切正常,但在 Eclipse 中我看到一个图标,当鼠标悬停时该图标显示为:“CarCounter 类型的静态方法 getCounter 应该以静态方式访问。”那么正确的方法是什么?

这是类:

public class CarCounter {
    static int counter = 0;

    public CarCounter(){
        counter++;
    }

    public static int getCounter(){
        return counter;
    }
}

这是我尝试访问变量计数器的地方:

public class CarCounterTest {
    public static void main( String args[] ){
        CarCounter a = new CarCounter();
        System.out.println(a.getCounter()); //This is where the icon is marked
    }
}

最佳答案

静态字段和方法不属于特定对象,而是属于类,因此您应该从类而不是从对象访问它们:

CarCounter.getCounter()

而不是

a.getCounter()

关于java - 在 Java 中访问静态字段的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5562321/

相关文章:

java - HashMap : can get value if key is hardcoded string but not if it is a variable

java - 如何使用自定义 TableModel 删除 JTable 中的行

java - 将用户输入从 editText 传递到 xml 中的 editText

SQL Server-声明局部变量 : "there is already an object named ' ' in the database"

html - 当我通过指向另一个 HTML 文件的链接传递一个变量时,CSS 配置消失了。发生这种情况的任何原因?

java - Spring 3 和 NTLM 身份验证

java - 从Java中的游戏中删除对象(eclipse)

c树结构表达式必须有类类型

c++ - 前向迭代器,如何返回 const 值

javascript - Angular 无意绑定(bind)/对象镜像