“非静态方法不能从静态上下文引用”错误 [英] "Non-static method cannot be referenced from a static context" error
问题描述
我有一个名为 Media
的类,它有一个名为 setLoanItem
的方法:
I have a class named Media
which has a method named setLoanItem
:
public void setLoanItem(String loan) {
this.onloan = loan;
}
我试图从一个名为 GUI
以下列方式:
public void loanItem() {
Media.setLoanItem("Yes");
}
但我得到错误
非静态方法setLoanItem(java.lang.String)不能从静态上下文中引用
non-static method setLoanItem(java.lang.String) cannot be referenced from a static context
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
),它需要order to function(因为它在实例上设置一个值( 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最好使用布尔值而不是包含Yes的字符串。)
(Btw it would be better to use a boolean instead of a string containing "Yes".)
这篇关于“非静态方法不能从静态上下文引用”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!