Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

class - What is the proper way of accessing static fields in Java?

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
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use CarCounter.getCounter(). That makes it clear that it's nothing to do with the object that the a variable's value refers to - the counter is associated with the type itself, rather than any specific instance of the type.

Here's an example of why it's really important:

Thread t = new Thread(runnable);
t.start();
t.sleep(1000);

What does it look like that code is doing? It looks like it's starting a new thread and then "pausing" it somehow - sending it to sleep for a second.

In fact, it's starting a new thread and pausing the current thread, because Thread.sleep is a static method which always makes the current thread sleep. It can't make any other thread sleep. That's a lot clearer when it's explicit:

Thread t = new Thread(runnable);
t.start();
Thread.sleep(1000);

Basically, the ability of the first snippet of code to compile is a mistake on the part of the language designers :(


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...