quot;Non-static method cannot be referenced from a static contextquot; error(“不能从静态上下文引用非静态方法错误)
问题描述
我有一个名为 Media
的类,它有一个名为 setLoanItem
的方法:
I have a class named Media
which has a method named setLoanItem
:
public void setLoanItem(String loan) {
this.onloan = loan;
}
我正在尝试通过以下方式从名为 GUI
的类中调用此方法:
I am trying to call this method from a class named GUI
in the following way:
public void loanItem() {
Media.setLoanItem("Yes");
}
但我得到了错误
不能从静态上下文引用非静态方法 setLoanItem(java.lang.String)
non-static method setLoanItem(java.lang.String) cannot be referenced from a static context
我只是想将 Media
类中的变量 onloan
更改为 GUI
类中的Yes".
I am simply trying to change the variable onloan
in the Media
class to "Yes" from the GUI
class.
我查看了具有相同错误消息但没有点击的其他主题!
I have looked at other topics with the same error message but nothing is clicking!
推荐答案
需要从实例调用实例方法.您的 setLoanItem
方法是一个实例方法(它没有修饰符 static
),它需要它才能起作用(因为它在调用它的实例 (this
)).
Instance methods need to be called from an instance. Your setLoanItem
method is an instance method (it doesn't have the modifier static
), which it needs to be in order to function (because it is setting a value on the instance that it's called on (this
)).
你需要先创建一个类的实例,然后才能调用它的方法:
You need to create an instance of the class before you can call the method on it:
Media media = new Media();
media.setLoanItem("Yes");
(顺便说一句,最好使用布尔值而不是包含是"的字符串.)
(Btw it would be better to use a boolean instead of a string containing "Yes".)
这篇关于“不能从静态上下文引用非静态方法"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“不能从静态上下文引用非静态方法"错误
基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01