[关闭]
@w1024020103 2017-01-24T16:58:04.000000Z 字数 1211 阅读 746

Cannot make a static reference to the non-static field solved

Java Eclipse static non-static reference


I have member variables like this:

  1. public class Solver {
  2. private List<Board> solutionBoards = new ArrayList<>();
  3. private boolean solved;

later I have codes like this:

  1. public boolean isSolvable(){
  2. return solved;
  3. }
  4. public int moves(){
  5. int moves;
  6. if(isSolvable()) {
  7. moves = solutionBoards.size() - 1;
  8. }
  9. else {
  10. moves = -1;
  11. }
  12. return moves;
  13. }

Eclispse says:

Cannot make a static reference to the non-static field solved
Cannot make a static reference to the non-static field solutionBoards

It offers me quick fix available:
Change 'solved' to 'static';
Change 'solutionBoards' to 'static'.

But why?

actually, I have codes like this:

  1. private static class SearchNode{
  2. private int moves;
  3. private Board board;
  4. private SearchNode prevNode;
  5. private SearchNode(Board board, int moves, SearchNode prevNode){
  6. this.board = board;
  7. this.moves = moves;
  8. this.prevNode = prevNode;
  9. }
  10. public int getMoves() {
  11. return moves;
  12. }
  13. public int getPriority(){
  14. return board.manhattan()+ moves;
  15. }
  16. public Board getBoard(){
  17. return board;
  18. }
  19. public SearchNode getPreviousNode(){
  20. return prevNode;
  21. }

Finally, I saw 'static'!
I guess SearchNode class has been somehow used by those two methods below, so that's where the 'static' issue comes. I deleted the static here and there's no error anymore. I haven't really thoroughly understand the static thing yet.

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注