What is the proper way of accessing static fields in Java?
Solution 1
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()
Solution 2
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 :(
Solution 3
That would be:
System.out.println(CarCounter.getCounter());
Solution 4
It is even possible, though highly discouraged, to write:
Math m = null;
double d = m.sin(m.PI/4.0);
System.out.println("This should be close to 0.5 " + (d*d));
This is because static accesses look at the declared type of the variable, and never actually dereference it.
enchance
Laravel, Wordpress, HTML, CSS, SCSS, Twig, and JS http://kaltencoder.com
Updated on September 15, 2020Comments
-
enchance over 3 years
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 } }
-
Andreas Dolk about 13 yearsreplace need by should as both lines of code are correct but the second one is discouraged
-
enchance about 13 yearsThis answered it for me; your answer was short at the same time concise. Amazing!
-
Jeremy B about 12 years@Binyamin Sharet I know this was an older question but your comment helped me through my project. Thank you!
-
Second Person Shooter about 6 yearsc# designers fixed this mistake.