“无法从静态上下文引用非静态方法”背后的原因是什么?

编程入门 行业动态 更新时间:2024-10-09 12:31:27
本文介绍了“无法从静态上下文引用非静态方法”背后的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

非常常见的初学者错误是当你尝试静态地使用类属性而不创建该类的实例时。它会留下您提到的错误消息:

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. You know why.. 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.

更多推荐

“无法从静态上下文引用非静态方法”背后的原因是什么?

本文发布于:2023-11-09 08:00:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571812.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   上下文   原因   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!