If somebody can explain why a static strategy cannot describe an instance varible? if possible please describe through an instance...
You are watching: Explain why a static method cannot refer to an instance variable
author and also iconoclast
posted 14 years ago
A static method have the right to describe an circumstances variable, however it must refer to an instance variable of a particular object. You do not need to usage a things to contact a static technique, right? So the static method has actually no object to describe, the way that non-static approaches describe "this". But if the static technique creates an circumstances of the course, or otherwise gets ahost of one, it deserve to access all the members of the course, consisting of the exclusive ones, via that instance; i.e., course Example int x; static void example() x = 3; // ILLEGAL Example e = new Example(); e.x = 3; // OK
posted 14 years ago
Here"s some example code that won"t compile: public course Examplepersonal int x; public Example()x = 0; public static void main(String args<>) System.out.println("Value of x: " + x); The compiler provides the adhering to error: non-static variable x cannot be referenced from a static context. or something to that impact. The factor that it will not compile is that the compiler realizes that you need to have actually an circumstances of the Example class in order to have an x variable. You don"t necessarily require an circumstances of the class in order to contact a static method. The compiler prevents you from accessing the circumstances variable from a context wright here tright here is no guarantee that an item has actually been instantiated.
See more: Why Is My Puff Bar Blinking Blue, New Puff Plus Blinking
Just a small various spin on what has actually already been said: One of my "learning experiences" was around this exceptionally topic. What I was doing was, inside of my public course yet prior to the main() method, I was establishing variables. Seemed like the point to execute. Then, the code inside my main() referenced those variables. Seemed favor the point to do aobtain. What I had to learn was....... main() is claimed static. A static approach can be dubbed without instantiating the course. NOW...the variables that I had claimed were incredibly certainly instance variables of my public class. Because main() is static and can be called without instantiating the class.... tright here was no object of the public course produced. Therefore, there is no circumstances variable to describe. That is why in many kind of resources I have actually checked out, the public course is instantiated right up at the height. NOW the variable/names exist.