编译错误将实例方法声明为静态上下文 (Java 6)

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

method2() 被定义为 class StaticVar 中的一个实例。意识到在 method2() 的上下文中,num 在 class Test 的对象中仍然没有内存分配。尽管我没有包含 static 修饰符

,但我收到 method2() 是静态的错误
  1. 将 method2() 设为静态后,它可以正常编译
  2. 在 method2() 中使用对象引用 class 测试它可以正常编译
  3. 但是出错了,为什么会被当作静态的?

    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();
        }
    }
    

得到这个编译结果:

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

"I'm getting an error that method2() is static" 不,它说 "static context" 并指向冒犯性表达:Test.num。也就是说,您正在尝试访问变量 num,就好像它是 class Test 的静态字段一样,而实际上它是一个实例字段,必须通过引用访问class 测试的对象 - 就像在 method1.

中正确完成的一样
  1. 为 num 添加适当的修饰符。

    static int num = 55;

  2. 如果你想从测试中获取非静态字段的值,请使用类似的东西。

测试:

public int num_1 = 55;
//so it's visible outside class

静态变量:

System.out.println("m2 num "+new Test().num_1);