如何实例化 类 并相互循环引用,而不必在 Java 中使用“NULL”?

How do you instantiate classes with cyclic references to each other without having to use `NULL` in Java?

假设您有以下 类 在 Java.

中完全合法
class Ping {
    Pong value;

    Ping(Pong value) { this.value = value; }
}

class Pong {
   Ping value;

   Pong(Ping value) { this.value = value; }
}

有没有办法在不给它们的构造函数一个 NULL 值的情况下创建 Pong 或 Ping 的实例?

你可以使用这样的东西

class Ping {
    Pong value;
    Ping() {this.value = new Pong(this)}
    Ping(Pong value) {this.value = value}
}
class Pong {
    Ping value;
    Pong() {this.value = new Ping(this)}
    Pong(Ping value) {this.value = value}
}

遗憾的是,这似乎是一种不好的做法,如下所述:Java leaking this in constructor。所以更好的实现是在创建 Ping 之后分配 Pong。

class Ping {
    Pong value;
    Ping() {}
    Ping(Pong value) {this.value = value}
    public setPong(Pong pong) {
        this.value = pong;
    }
}
class Pong {
    Ping value;
    Pong() {}
    Pong(Ping value) {this.value = value}
    public setPing(Ping ping) {
        this.value = ping;
    }
}
Ping ping = new Ping();
Pong pong = new Pong(ping);
ping.setPong(pong);