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?
Here's the class:
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()
and not
a.getCounter()
初学者在使用Java时遇到关于静态字段的问题。在Eclipse中,如何避免提示‘静态方法getCounter应以静态方式访问’?本文解释了静态字段的使用规则,并给出了正确的访问方式:直接通过CarCounter类名调用getCounter方法。
1410

被折叠的 条评论
为什么被折叠?



