Any nice way to make two immutable objects refer to eachother?

后端 未结 7 2360
自闭症患者
自闭症患者 2021-02-13 04:53

Take these two Java classes:

class User {
   final Inventory inventory;
   User (Inventory inv) {
       inventory = inv;
   }
}

class Inventory {
   final User         


        
7条回答
  •  伪装坚强ぢ
    2021-02-13 05:40

    You can do it if you don't need to inject one of the objects.

    class User {
       private final Inventory inventory;
       User () {
           inventory = new Inventory(this);
       }
    }
    

提交回复
热议问题