在 Java 中访问静态字段的正确方法是什么? [英] What is the proper way of accessing static fields in Java?

查看:25
本文介绍了在 Java 中访问静态字段的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I just started learning Java and I wrote a class to test using static fields. Everything works fine but in Eclipse I see an icon which when hovered comes out as: "The static method getCounter from the type CarCounter should be accessed in a static way." What's the right way then?

这是课程:

public class CarCounter {
    static int counter = 0;

    public CarCounter(){
        counter++;
    }

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

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

And here's where I try to access variable 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
    }
}

推荐答案

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

Static fields and methods are not belong to a specific object, but to a class, so you should access them from the class, and not from an object:

CarCounter.getCounter()

而不是

a.getCounter()

这篇关于在 Java 中访问静态字段的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆