Wednesday, July 14, 2021

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

"non-static variable cannot be referenced from a static context" is the biggest nemesis of someone who has just started programming and that too in Java. Since the main method in java is the 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 the main in Java which is static. if you want to know why the 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 the non-static variable can not be called from static method

non-static variable cannot be referenced from a static contextNow before finding the answer of compiler error "non-static variable cannot be referenced from a static context", let's have a quick revision of static. The static variable in Java belongs to Class and its value remains the same for all instances

static variable initialized when class is loaded into JVM on the other hand instance variable has a different value for each instance and they get created when an instance of an object is created either by using the 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, the only reason which makes sense to disallow non-static or instance variable inside static context is the non-existence of instance.



In Summary, since code in static context can be run even without creating an instance of a class, it does not make sense asking value for a 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 why non-static variables cannot be referenced from a static context.


Other Java Tutorials you may find useful:

11 comments:

  1. 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".

    ReplyDelete
  2. 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

    ReplyDelete
  3. 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

    ReplyDelete
  4. 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.

    ReplyDelete
  5. 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());

    }

    }

    ReplyDelete
    Replies
    1. It will throw an error since you are trying to access a non static variable through a static method. .

      Delete
  6. 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..

    ReplyDelete
  7. 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);

    }
    }

    ReplyDelete
  8. @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();

    ReplyDelete
  9. class Student{
    int rno,m1,m2,m3;
    Student(int x,int y,int z,int w){

    }
    class ReportCard{
    int calculate(Student s1){
    int total = s1.m1+s1.m2+s1.m3;
    return total;
    }
    }
    public static void main(String[] ar){
    Student s = new Student(10,30,40,50);
    ReportCard rc = new ReportCard();
    int res = rc.calculate(s);
    System.out.println("Result: "+res);

    }
    }

    .
    .
    .
    .
    .
    .
    I got the same error in this code.Can anyone plz help me in this????

    ReplyDelete
    Replies
    1. Parameters that you have passed through the constructor are not at all assigned to the respective values..

      Delete