Search code examples
javastatic-methodsinstance-variablesjava-6

Compilation error is stating the instance method as a static context (Java 6)


method2() is defined as an instance in class StaticVar. Having been aware that in method2()'s context, num still doesn't have memory allocation in class Test's object. I'm getting an error that method2() is static although I didn't include static modifier

  1. With making method2() as static, it compiles fine
  2. With an object reference in method2() for class Test it compiles fine
  3. But upon error, why is it being treated as static?

    class Test 
    {
        int num = 55;
    
        static void method1()
        { Test t2 = new Test(); System.out.println("m1 num "+t2.num);}
    }
    
    class StaticVar
    {
        void method2()
        {  System.out.println("m2 num "+Test.num);}  //error here
    
        public static void main(String []args)
        {
            StaticVar sv = new StaticVar();
            Test.method1();
            sv.method2();
        }
    }
    

Got this compilation result:

D:\JavaEx>javac StaticVar.java StaticVar.java:12: non-static variable num cannot be referenced from a static context

{ System.out.println("m2 num "+Test.num);}


Solution

  • "I'm getting an error that method2() is static" No, it says "static context" and points to the offensive expression: Test.num. That is, you are trying to access variable num as if it is a static field of the class Test, while in fact it is an instance field and must be accessed via reference to an object of class Test - just like it is correctly done in the method1.