Why static method cannot access non static variables

public class StaticTest {

    private int count=0;
    public static void main(String args[]) throws IOException {
        count++; //compiler error: non-static variable count cannot be referenced from a static context
    }
 }

Static variable in Java belongs to Class and its value remains same for all instance.
Static variable initialized when class is loaded into JVM on the other hand instance variable has different value for each instances and they get created when instance of an object is created either by using new() operator or using reflection like Class.newInstance().
 So if you try to access a non static variable without any instance compiler will complain because those variables are not yet created and they don’t have any existence until an instance is created and they are associated with any instance.

   So in my opinion only reason which make sense to disallow non static or instance variable inside static context is non existence of instance.

In summary since code in static context can be run even without creating any instance of class, 
it does not make sense asking value for an specific instance which is not yet created.



How to access non static variable inside static method or block

We can access any non static variable inside any static method or block by creating an instance of class in Java and using that instance to reference instance variable. This is the only legitimate way to access non static variable on static context.

public class StaticTest {
    private int count=0;
    public static void main(String args[]) throws IOException {
        StaticTest test = new StaticTest(); //accessing static variable by creating an instance of class
        test.count++;
    }

 }

Advertisements
This entry was posted in java. Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s