Wednesday, February 15, 2012

Why non-static variable cannot be referenced from a static context?

"non-static variable cannot be referenced from a static context" is biggest nemesis of some one who has just
started programming and that too in Java. Since main method in java is most popular method among all beginners and
they try to put program code there they face "non-static variable cannot be referenced from a static context" compiler error when they  try to access a non static member variable inside main in Java which is static. if you want to know
why main is declared static in Java see the link.

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
    }
  
 
}

Why non static variable can not be called from static method

non-static variable cannot be referenced from a static contextNow before finding answer of compiler error "non-static variable cannot be referenced from a static context", let's have a quick revision of static. 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

You can still 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. here is a code example of accessing non static variable inside 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++;
    }  
 
}


So next time if you get compiler error “non-static variable cannot be referenced from a static contextaccess static member by creating an instance of Class. Let me know if you find any other reason on why non-static variable cannot be referenced from a static context.

Other Java Tutorials you may find useful:

8 comments :

Limyong said...

This rule not only apply to static variable but also on static methods. if you call any non static method inside any static method like main you will get "non static method cannot be referenced from a static context". Same is true for special variables "this" and "super" which are non static and if you use this inside static method you will get "non static variable this cannot be referenced from a static context" or "non static variable super cannot be referenced from a static context".

Matt said...

Thank you for this resource. Together with other articles on your blog it saved me hours of my life and i'm happy to learn/understand these things more thoroughly!
Matt

Mohit Kashyap said...

This would not work . Non static variables,objects,or any costructor would always give error when referenced from a static context . Not Possible . Because static are meant to be made for the first priority of innitialization . Means STATICS are always innitialize first. Thats-why main is always static . Becoz main is the entry point and it must be run first so the remaining class can execute . And non statics are low priority . They only executes when they called .In other words we can say STATIC is predefine and non statics are user define ,according to will . To differentiate between static and non static and also to resolve the problem of clashig between STATICS and NON-STATICS every platform gives this utility . Yup this is a utility

Pushkar said...

Hello Javin, can you please help with how to call a non static method from main method in Java. I am getting the same error "non-static method getDate() cannot be referenced from a static context", I need this method from main, which is static method. Please advise.

Sports Follower said...

Find output:

public class MyClass {

int myVar;



public static void setMyVar(int myVar)

{

this.myVar = myVar;

}

public int getMyVar()

{

return this.myVar;

}



public static void main(String args[])

{

MyClass mc = new MyClass();

mc.setMyVar(10);

System.out.println(mc. getMyVar());

}

}

Anonymous said...

Thank you for you clear, concise, straightforward explanation. That is all that is necessary to help a brother out. You wouldn't think it would be so hard to find a clear thinker..

Qaiser Muhammad said...

I am sorry friends this didnt work for me.

package JavaLearning;

public class MainFile{

int abc=8;

public static void main(String[] args) {

Mainfile mF = new MainFile();

System.out.println("Add is "+mF.abc);

}
}

Srihari Goud said...

@Qaiser Muhammad: You made a mistake. Mainfile mF = new MainFile(); in this line you given class name wrong. You used lower case of 'f' in Mainfile.
just replace following it execute fine,
MainFile mF = new MainFile();

Post a Comment