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 :(
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…