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
}
}
By using static variables a single copy is shared among all the instances of the class, and they can be accessed directly by class name and don't require any instance. The Static method similarly belongs to the class and not the instance and it can access only static variables but not non-static variables.
You cannot access a non-static field from a static method, unless you first create an instance and access that instance's field. You can return the instance from the static method, so that the caller can see the set instance field.
Static variables can be accessed by calling the class name of the class. There is no need to create an instance of the class for accessing the static variables because static variables are the class variables and are shared among all the class instances.
Static variables can be accessed by calling with the class name ClassName. VariableName. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.
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()
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 :(
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With