【问题标题】:Binding static class var to non-static instance var confusion. Works when creating a new object? [duplicate]将静态类 var 绑定到非静态实例 var 混淆。创建新对象时有效吗? [复制]
【发布时间】:2021-02-09 20:55:39
【问题描述】:

假设我面前有以下代码:

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

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

【问题讨论】:

  • 没有名为A.b 的东西。 b 是非静态的,所以你可以得到一个的唯一方法是someInstanceOfACreatedWithNew . b 换句话说......请研究它实际上在你添加 static时的含义> 到内部类的定义。

标签: java variables static initialization


【解决方案1】:

您看到的更像是 IDE 生成的“工具提示”,因为鼠标悬停在 IDE 上是一个功能,与编译器无关。显示的消息完全取决于 IDE,如果您更改 IDE,可能会发生变化。
只有在实际尝试编译代码时才会看到编译器错误。

这两行都无法编译的原因是,在每种情况下,您都试图访问没有实例的实例绑定字段,即“A.b”。
其他两行编译是因为在这两种情况下,您都创建了类的新实例并通过它访问实例绑定字段,也就是 new A().b

【讨论】:

    【解决方案2】:
        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 声明所迷惑。这意味着嵌套类可以在不需要封闭类的实例的情况下被实例化。这并不意味着它的字段或方法可以自动静态访问。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-27
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多