To be specific, I was trying this code:
package hello;
public class Hello {
Clock clock = new Clock();
public static void main(String args[]) {
clock.sayTime();
}
}
But it gave the error
Cannot access non-static field in static method main
So I changed the declaration of clock
to this:
static Clock clock = new Clock();
And it worked. What does it mean to put that keyword before the declaration? What exactly will it do and/or restrict in terms of what can be done to that object?
Static makes the clock member a class member instead of an instance member. Without the static keyword you would need to create an instance of the Hello class (which has a clock member variable) - e.g.
I have developed a liking for static methods (only, if possible) in "helper" classes.
The calling class need not create another member (instance) variable of the helper class. You just call the methods of the helper class. Also the helper class is improved because you no longer need a constructor, and you need no member (instance) variables.
There are probably other advantages.
The
static
keyword in Java means that the variable or function is shared between all instances of that class as it belongs to the type, not the actual objects themselves.So if you have a variable:
private static int i = 0;
and you increment it (i++
) in one instance, the change will be reflected in all instances.i
will now be 1 in all instances.Static methods can be used without instantiating an object.
In Java, the
static
keyword can be simply regarded as indicating the following:If you think of
static
in this way, it becomes easier to understand its use in the various contexts in which it is encountered:A
static
field is a field that belongs to the class rather than to any particular instanceA
static
method is a method that has no notion ofthis
; it is defined on the class and doesn't know about any particular instance of that class unless a reference is passed to itA
static
member class is a nested class without any notion or knowledge of an instance of its enclosing class (unless a reference to an enclosing class instance is passed to it)Can also think of static members not having a "this" pointer. They are shared among all instances.
A field can be assigned to either the class or an instance of a class. By default fields are instance variables. By using
static
the field becomes a class variable, thus there is one and only oneclock
. If you make a changes in one place, it's visible everywhere. Instance varables are changed independently of one another.