非静态变量 this 不能从静态上下文中引用 - 为什么在这里?
我有一个代码:
package why;
public class Foo
{
public class Foo1
{
String bar;
public Foo1(String bar)
{
this.bar = bar;
}
public static Foo1 MYCONSTANT = new Foo(null);
}
}
为什么我会得到“不能从静态上下文引用的非静态变量”? 我分配非静态类的实例。
为什么还要在这里?
public static Foo getMYCONSTANT()
{
return new Foo(null, null);
}
谢谢
I have a code:
package why;
public class Foo
{
public class Foo1
{
String bar;
public Foo1(String bar)
{
this.bar = bar;
}
public static Foo1 MYCONSTANT = new Foo(null);
}
}
Why do I get 'non-static variable this cannot be referenced from a static context'?
I allocate the instance of non-static class.
Why even here?
public static Foo getMYCONSTANT()
{
return new Foo(null, null);
}
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
让我们看一下这个例子:
问题是
NonStaticClass
是非静态。非静态内部类不能包含静态字段。如果你想在内部类中拥有静态字段,你需要将类设置为静态。
来自java文档:
有关更多信息,请查看嵌套类
Lets take a look at this example:
The problem is that
NonStaticClass
is, well, not static. A non static inner class can't contain static fields.If you want to have a static field in the inner class you need to make the class static.
From the java documentation:
For more information take a look at Nested Classes
我不确定你真正的问题是什么......但这也许会有所帮助:
I'm not sure what your real question is ... but perhaps this might help: