Search code examples
javaclassstatic-methods

Java non-static variable reference error?


    public class Abc {
     int a = 9;
     static void print() {
         System.out.println(a);
    }
}
class AbcTester {
    public static void main(String[] args) {
        Abc test = new Abc();
        test.a = 8;
        test.print();
    }
}

Why does the code produce a "java: non-static variable a cannot be referenced from a static context" error even, though I have created an instance of the class in the main method. I know that static methods cannot use non-static fields, but after I've created an instance of the class, shouldn't the method be able to work on it?


Solution

  • You can't refer to an instance field from a static context.

       public class Abc {
         int a = 9;             // <-- instance field
         static void print() {  // <-- static context (note the static keyword)
             System.out.println(a); // <-- referring to the int field a.
         } 
       }
    

    The reason is that static methods are shared across their classes. And static methods do not require an explicit instance of the class to be invoked. So if you try to access an instance field (a in your case) from a static context, it has no idea which class instance to refer to. Therefore it doesn't know which class's instance field of a to access.