为什么这个java代码显示“非静态变量,这不能从静态上下文引用”错误?

时间:2014-08-13 09:20:35

标签: java compiler-errors non-static

package ttt2;
import java.util.Scanner;
public class TTT2 {
    public class State{
        int[][] sheet;
        int childCount;
        public void initialize(int n,int[][] lastState,int level){
            sheet=new int[n][n];
            childCount=n*n-1;
            State[] nextState=new State[childCount];
            nextState[0].initialize(n,sheet,level+1);
            int turn=level%2+1;
        }
    }
    public static void main(String[] args) {
        System.out.print("Enter the size(n) of the sheet(n*n):");
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int[][] matrix=new int[n][n];
        State s=new State();
    }

}

无论我尝试什么,我都有这个问题。我尽我所能。 在声明State类的对象时,它显示错误"非静态变量,这不能从静态上下文中引用"

5 个答案:

答案 0 :(得分:2)

这是因为非静态内部类需要实例化封闭类的实例,并且您尝试从静态上下文中执行此操作:

public class TTT2 {
    public class State{ // <- non-static
    }
    public static void main(String[] args) {
        State s=new State(); // <- static context
    }
}

您有两种选择。一个是创建内部类static,因此它不再需要一个封闭的类实例:

public class TTT2 {
    public static class State{ // <- static
    }
    public static void main(String[] args) {
        State s=new State(); // <- no problem
    }
}

另一个是实例化一个新的TTT2用作封闭实例,缺点是你创建了一个TTT2你可能不会用于其他任何东西(至少在你的例子中):

public class TTT2 {
    public class State{ // <- non-static
    }
    public static void main(String[] args) {
        State s=new TTT2().new State(); // <- no problem
    }
}

答案 1 :(得分:1)

虽然我没有得到指定的异常而是显示(在eclipse中)

  

无法访问TTT2类型的封闭实例。必须符合资格   使用TTT2类型的封闭实例进行分配(例如x.new A()   其中x是TTT2的实例。

State s=new TTT2().new State(); 

这是创建内部对象创建的正确方法。

答案 2 :(得分:1)

State类没有封闭的实例。创建TTT2的外部实例或将State声明为static

State state = new TTT2().new State();

答案 3 :(得分:1)

将状态类声明为

public static class State {
    // ...
}

你应该被设定。这是因为没有静态修饰符的State类只能通过保持类的实例访问,因此,静态方法不应该能够访问它,因为它不知道要使用哪个实例。 / p>

使State静态允许它在没有外部类的实例的情况下进行实例化。

答案 4 :(得分:1)

由于StateTTT2的嵌套类,因此每个State对象都会得到一个TTT2对象 - 因此您应该将State声明为{ {1}}在静态上下文中使用或使用public static class State

实例化时