This week's giveaway is in the Java/Jakarta EE forum. We're giving away four copies of Java EE 8 High Performance and have Romain Manni-Bucau on-line! See An instance variable is defined by the class but it is owned by the object that is intantiated from the class. In other words, if you haven't instantiated one yet...... then it doesn't exist. That is why a static method can not see an instance variable or method.
A static variable is owned by the class itself and exists without the need for an instantiated object. Rather than a reference variable to an instance of the object, it's reference must be anchored by the class name itself.
Another point that I have not seen above is that, static methods/variables are shared by ALL INSTANCES of the CLASS that declares them. THAT is why they are often used as flags/counters across MULTIPLE objects. Because each individual object points to the same variable or method.
So, when a new object is instantiated, each instance variable is a new copy, unique to THAT particular instantiated object. each static variable is a single copy that each individually instantiated object points to... the very same one is shared.
A little difference in talking about methods..... this might seem a little confusing but just try to think it over a bit....
All methods are shared.... there are just two ways that we need to understand. (for the MOMENT, just for simplicity, I am omitting any discussion of threading/synchronization issues, just to make presentation a little clearer on the point.)
1) An instance method is a shared routine that is safe to share because each object that refers to it has it's own state, it's own variables. BUT when it is called... an instantiated object IS in CONTEXT. Meaning that there IS one associated with this method. Thus an instance variable must be anchored to some instance of an object (even if it is "this" object inferred as in .... this.methodName() ).
2) A static method is shared but there is no specific object associated with this invocation of the method so there are no instance variables/or instance methods visible. You cant see them from the static method... so you can't refer to them.
But a static can refer to static variables and static methods as allowed by access modifiers.
SCJP - 86% - June 11, 2009