javacyclic-reference

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


Suppose that you have the following classes which are perfectly legal in Java.

class Ping {
    Pong value;

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

class Pong {
   Ping value;

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

Is there any way to create an instance of Pong or Ping without giving their constructors a NULL value?


Solution

  • You could use something like this

    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}
    }
    

    Sadly this seems to be bad practice as described here: Java leaking this in constructor. So a better implementation would be to assign Pong after the creation of Ping.

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