• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why a Static method cannot refer to an instance variable?  RSS feed

 
Sunali Anu
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If somebody can explain why a static method cannot refer to an instance varible? if possible please explain with an example...
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.,

 
Bill Cruise
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's some example code that won't compile:



The compiler gives the following error:

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
Posts: 320
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!