这是我的简单课程:
public class Project {
private int size;
private Obj tree;
static Obj insert( Obj t, String s ) { // t is null
t = new Obj();
t.val = s;
return t;
}
public Project()
{
Obj tree = new Obj();
int size=0;
}
public class Obj
{
public String val;
public Obj()
{
val=null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试在insert()函数中创建一个新对象时,我收到此错误:
Error: non-static variable this cannot be referenced from a static context
Run Code Online (Sandbox Code Playgroud)
你的Obj类不是static==它是一个内部类.这意味着它需要一个封闭类的实例Project来生存.
从该static方法insert,没有这样的Project实例,因此编译器错误.
该Obj级似乎并不需要任何实例变量Project,所以没有理由保持它非static.使Obj类static在Project.
public static class Obj
Run Code Online (Sandbox Code Playgroud)