我有一个名为SharedBoard
的对象,它是一个静态实体,因此我希望所有类都可以共享它。我有这个方法getBoard()
,它返回SharedBoard
对象。但是,当我尝试从另一个类调用此方法时,总是得到一个NullPointerException
。实际上,我什至无法通过这种方法在板上印刷元素。我在某处缺少OOP概念吗?
public class Server {
private ServerSocket serverSocket;
private static SharedBoard board;
// The set of all the print writers for all the clients, used for broadcast.
private Set<PrintWriter> writers = new HashSet<>();
public Server(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
Server.board = new SharedBoard();
}
public static SharedBoard getBoard() {
for(int i=0; i<9; i++)
System.out.println(board.moves[i]);
return board;
}
这是
SharedBoard
类/构造函数的一部分:public class SharedBoard {
private final Object lock = new Object();
int[] moves;
SharedBoard() {
moves = new int[9];
for(int i=0; i<9; i++)
moves[i] = 0;
}
.
.
.
}
最佳答案
Server
类的构造方法未调用。因此,语句Server.board = new SharedBoard();
不会被调用,并且它将始终为null。因此,您可以从此语句的System.out.println(board.moves[i]);
中获得NPE。
我们可以通过解决
从构造函数初始化服务器对象或使用静态初始化程序块初始化板对象
class Server {
private ServerSocket serverSocket;
private static SharedBoard board;
static {
board = new SharedBoard();
}
// The set of all the print writers for all the clients, used for broadcast.
private Set<PrintWriter> writers = new HashSet<>();
public Server(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
}
public static SharedBoard getBoard() {
for (int i = 0; i < 9; i++)
System.out.println(board.moves[i]);
return board;
}
}
或直接在课堂上初始化
private static SharedBoard board= new SharedBoard();
关于java - 无法访问类的静态元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59403206/