本文介绍了“不能从静态上下文中引用非静态方法"背后的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
非常常见的初学者错误是当您尝试静态地"使用类属性时无需创建该类的实例.它给您留下了提到的错误消息:
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:
您可以使非静态方法成为静态方法,也可以使该类的实例使用其属性.
这背后的原因是什么?我不关心解决方案,而关心原因.
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.
这篇关于“不能从静态上下文中引用非静态方法"背后的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!