首页 > 解决方案 > 将静态类 var 绑定到非静态实例 var 混淆。创建新对象时有效吗?

问题描述

假设我面前有以下代码:

public class Theory {

public static void main(String[] args) {
        new Theory().program();
    }

void program(){
A.a = A.b;             //won't compile
A.a = new A().b;    

A.b = A.a;             // won't compile either
new A().b = A.a

}

static class A{
    static int a;
    int b;
  }
}

当我将鼠标悬停在代码上时,它说“无法从静态上下文引用非静态字段”,我有点理解,但我无法理解为什么连续行不显示编译器错误?

标签: javavariablesstaticinitialization

解决方案


    A.a = A.b;           // You can't reference an instance field (b) statically
    A.a = new A().b;     // You create an instance of A, use it to access 'b' and assign
                         // it to 'a' which you can access statically.  This is okay.                      

    A.b = A.a;           // You can't reference an instance field (b) statically
    new A().b = A.a;     // This works, but the instance is gone (not 
                         // assigned anywhere) once the assignment is complete.
 
    
    static class A {
        static int a;
        int b;
    }

笔记。不要被static class声明所迷惑。这意味着嵌套类可以在不需要封闭类的实例的情况下被实例化。这并不意味着它的字段或方法可以自动静态访问。


推荐阅读