“不能从静态上下文中引用非静态方法";错误

编程入门 行业动态 更新时间:2024-10-10 14:22:15
本文介绍了“不能从静态上下文中引用非静态方法";错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个名为 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".)

更多推荐

“不能从静态上下文中引用非静态方法";错误

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

发布评论

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

>www.elefans.com

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