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
- With making method2() as static, it compiles fine
- With an object reference in method2() for class Test it compiles fine
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);}