java - 将静态类 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;
}
}
当我将鼠标悬停在代码上时,它说“无法从静态上下文引用非静态字段”,我有点理解,但我无法理解为什么连续行不显示编译器错误?
解决方案
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
声明所迷惑。这意味着嵌套类可以在不需要封闭类的实例的情况下被实例化。这并不意味着它的字段或方法可以自动静态访问。
推荐阅读
- verilog - 如何在 kristen 中创建多个常见的 FPGA 结构?
- ember.js - 即使创建了适配器也返回 401 Unauthorized
- php - 由于某种原因,提交按钮无法通过 POST 表单方法工作?
- excel - 在 excel 中创建多级 WBS 级别列表?任务 1.1,子任务 1.1.1
- node.js - 在 Windows 的 node.js 应用程序中安装包裹捆绑器时出错
- javascript - 有没有一种有效的方法可以将许多文档快速上传到 Google Firestore?
- java - 缓解 Java 中针对 https 请求的会话劫持
- javascript - 使用来自 Axios.get() 的数据在我的 React 组件中呈现
- javascript - 当对象是函数时,为什么 module.export 返回未定义?
- python - 从 pytest_generate_tests 方法在 junit xml 中添加日志