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?
staticmembers belong to the class instead of a specific instance.It means that only one instance of a
staticfield exists[1] even if you create a million instances of the class or you don’t create any. It will be shared by all instances.Since
staticmethods also do not belong to a specific instance, they can’t refer to instance members. In the example given,maindoes not know which instance of theHelloclass (and therefore which instance of theClockclass) it should refer to.staticmembers can only refer tostaticmembers. Instance members can, of course accessstaticmembers.Side note: Of course,
staticmembers can access instance members through an object reference.Example:
[1]: Depending on the runtime characteristics, it can be one per ClassLoader or AppDomain or thread, but that is beside the point.