JAVA“非静态变量,这不能从静态上下文中引用”
问题描述:
我来自C++并从Java开始。所以我知道我不能使用超级和静态函数,但最新的代码有什么问题?JAVA“非静态变量,这不能从静态上下文中引用”
class TestClass {
public static void main(String[] args) {
Test x = new Test(); // Here is the error Why?
}
class Test {
//attributes
String attribute;
}
}
Thx for your help!
答
Test
class是TestClass
类的内部类。因此,为了创建Test
类的对象,您必须创建一个包含TestClass
类的对象。
可以通过移动Test
类外TestClass
解决这个错误:
class Test {
//attributes
String attribute;
}
class TestClass {
public static void main(String[] args) {
Test x = new Test();
}
}
或通过使其嵌套(静态)类(其不需要包围实例):
class TestClass {
public static void main(String[] args) {
Test x = new Test();
}
static class Test {
//attributes
String attribute;
}
}
如果你坚持保持Test
一个内部类,你可以写:
class TestClass {
public static void main(String[] args) {
TestClass.Test x = new TestClass().new Test();
}
class Test {
//attributes
String attribute;
}
}
答
因为,Test
是非静态类,并试图从静态上下文中访问它(即,从main()方法,这是静态的),这意味着您需要首先创建TestClass
类的实例/对象。
Test x = new Test();
应该
TestClass.Test x = new TestClass().new Test();
或者声明Test
为静态。
static class Test {
//attributes
String attribute;
}