我刚开始学习 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/