This question already has answers here:
Why do I get “non-static variable this cannot be referenced from a static context”?

(8个答案)


6年前关闭。



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类的对象时,它显示错误“无法从静态上下文引用的非静态变量”

最佳答案

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

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
    }
}

关于java - 为什么此Java代码显示 “non-static variable this cannot be referenced from a static context”错误? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25282530/

10-09 05:56
查看更多