non-static variable this cannot be referenced from a static context

前端 未结 2 1992
我寻月下人不归
我寻月下人不归 2020-12-16 23:10

The error comes from this line BoardState addme = new BoardState();

For some reason the non-static variable that it is pointing at is \"new\". I am unclear of h

相关标签:
2条回答
  • 2020-12-16 23:54

    The reason it doesn't work is because your class BoardState is an inner, non-static, class inside of IntelligentTicTacToe. This means that when referring to it, you'll be referring to an instance of the class; the instance isn't available from a static context.

    One solution is to declare that class as:

    public static class BoardState {
    

    You can read more on inner classes here.

    0 讨论(0)
  • 2020-12-17 00:04

    Don't nest classes like you're doing. There's no need, and all it's going to do is to require that you create a BoardState object on top of an IntelligentTicTacToe instance, i.e.,

    BoardState addme = new IntelligentTicTacToe(). new BoardState();
    

    but this should not be a requirement of your program.

    Solution: Put the BoardState class where it belongs, in its own file. Or make BoardState an enum, but then it should only hold constants.

    0 讨论(0)
提交回复
热议问题