非常常见的初学者错误是当您尝试"静态"使用类属性而不创建该类的实例时.它会留下您提到的错误消息:
您可以将非静态方法设为静态,也可以使该类的实例使用其属性.
为什么?我不是要求解决方案.我很高兴知道它背后的原因是什么.核心原因!
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();
}
Run Code Online (Sandbox Code Playgroud) 我有一个名为的类Media,它有一个名为的方法setLoanItem:
public void setLoanItem(String loan) {
this.onloan = loan;
}
Run Code Online (Sandbox Code Playgroud)
我试图从以GUI下列方式命名的类中调用此方法:
public void loanItem() {
Media.setLoanItem("Yes");
}
Run Code Online (Sandbox Code Playgroud)
但是我收到了错误
非静态方法setLoanItem(java.lang.String)不能从静态上下文引用
我只是试图onloan将Media类中的变量更改为"是" GUI.
我看过其他主题有相同的错误消息,但没有点击!
首先是一些代码:
import java.util.*;
//...
class TicTacToe
{
//...
public static void main (String[]arg)
{
Random Random = new Random() ;
toerunner () ; // this leads to a path of
// methods that eventualy gets us to the rest of the code
}
//...
public void CompTurn (int type, boolean debug)
{
//...
boolean done = true ;
int a = 0 ;
while (!done)
{
a = Random.nextInt(10) ;
if (debug) { int i = 0 ; while (i<20) …Run Code Online (Sandbox Code Playgroud)