A static method can refer to an instance variable, but it must refer to an instance variable of a specific object. You don't need to use an object to call a static method, right? So the static method has no object to refer to, the way that non-static methods refer to "this". But if the static method creates an instance of the class, or otherwise gets ahold of one, it can access all the members of the class, including the private ones, through that instance; i.e.,
non-static variable x cannot be referenced from a static context.
or something to that effect. The reason that it won't compile is that the compiler realizes that you have to have an instance of the Example class in order to have an x variable. You don't necessarily need an instance of the class in order to call a static method. The compiler prevents you from accessing the instance variable from a context where there is no guarantee that an object has been instantiated.
Bob Ruth
Ranch Hand
Joined: Jun 04, 2007
Posts: 318
posted
0
Just a little different spin on what has already been said:
One of my "learning experiences" was about this very topic. What I was doing was, inside of my public class but before the main() method, I was establishing variables. Seemed like the thing to do. Then, the code inside my main() referenced those variables. Seemed like the thing to do again.
What I had to learn was....... main() is declared static. A static method can be called without instantiating the class. NOW...the variables that I had declared were very definitely instance variables of my public class.
Since main() is static and can be called without instantiating the class.... there was no object of the public class created. Therefore, there is no instance variable to refer to.
That is why in many sources I have seen, the public class is instantiated right up at the top. NOW the variable/names exist.
------------------------
Bob
SCJP - 86% - June 11, 2009
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.
subject: Why a Static method cannot refer to an instance variable?