爪哇语;非静态变量不能从静态上下文引用此变量; 我来自C++,从java开始。所以我知道我不能在静态函数中使用super和this,但是代码有什么问题吗 class TestClass { public static void main(String[] args) { Test x = new Test(); // Here is the error Why? } class Test { //attributes String attribute; } }

爪哇语;非静态变量不能从静态上下文引用此变量; 我来自C++,从java开始。所以我知道我不能在静态函数中使用super和this,但是代码有什么问题吗 class TestClass { public static void main(String[] args) { Test x = new Test(); // Here is the error Why? } class Test { //attributes String attribute; } },java,static,Java,Static,谢谢你的帮助 Test类是TestClass类的内部类。因此,为了创建Test类的对象,必须创建包含TestClass类的对象 您可以通过将Test类移到TestClass外部来修复此错误: class Test { //attributes String attribute; } class TestClass { public static void main(String[] args) { Test x = new Test(); }

谢谢你的帮助

Test
类是
TestClass
类的内部类。因此,为了创建
Test
类的对象,必须创建包含
TestClass
类的对象

您可以通过将
Test
类移到
TestClass
外部来修复此错误:

class Test {
    //attributes 
    String attribute;
}

class TestClass { 
    public static void main(String[] args) {
        Test x = new Test();
    }  
}
或者使其成为嵌套(静态)类(不需要封闭实例):

如果坚持保持
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;
}
static class Test {
    //attributes 
    String attribute;
}