What is the reason behind quot;non-static method cannot be referenced from a static contextquot;?(“无法从静态上下文引用非静态方法背后的原因是什么?)
问题描述
非常常见的初学者错误是当您尝试静态"使用类属性时.没有创建该类的实例.它会给您留下上述错误消息:
The very common beginner mistake is when you try to use a class property "statically" without making an instance of that class. It leaves you with the mentioned error message:
您可以将非静态方法设为静态或将该类的实例设为使用其属性.
You can either make the non static method static or make an instance of that class to use its properties.
这背后的原因是什么?我关心的不是解决方案,而是原因.
private java.util.List<String> someMethod(){
/* Some Code */
return someList;
}
public static void main(String[] strArgs){
// The following statement causes the error.
java.util.List<String> someList = someMethod();
}
推荐答案
你不能调用不存在的东西.由于您尚未创建对象,因此非静态方法尚不存在.静态方法(根据定义)始终存在.
You can't call something that doesn't exist. Since you haven't created an object, the non-static method doesn't exist yet. A static method (by definition) always exists.
这篇关于“无法从静态上下文引用非静态方法"背后的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“无法从静态上下文引用非静态方法"背后的原因是什么?


- 转换 ldap 日期 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 获取数字的最后一位 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01