无法访问类的静态元素

时间:2019-12-19 04:12:04

标签: java class oop methods

我有一个名为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;
    }

.
.
.
}


2 个答案:

答案 0 :(得分:2)

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();

答案 1 :(得分:1)

在加载类时,所有静态成员都将初始化并以默认值加载到内存中。因此, SharedBoard 是Server类的静态变量,这就是为什么 SharedBoard 用默认值即null初始化的原因。

因此,在加载静态变量时,您必须在SIB(静态块)中手动实例化 SharedBoard ,例如...

static {
     board = new SharedBoard();
}