Java: Alternative to passing “this” as constructor argument in order to reference creating object

前端 未结 3 1317
轮回少年
轮回少年 2021-02-14 07:05

I\'ve spent a while thinking about different solutions that the one I went for as I\'ve read around (I am not really experienced with Java yet) that using this for a constructor

3条回答
  •  臣服心动
    2021-02-14 07:39

    Generally there is no magic. You can either pass parameter via constructor or initalize it later using setter/init method etc.

    If your class JobMod needs reference to JobGroupMod and has nothing to do without it pass it using constructor. If sometimes it can stand without it create init() method or setter that can initialize this reference.

    BTW sometimes you have to create both parameterized and default constructor: first for regular programmatic usage, second if you are using XML, JSON or other serialization that is going easier for bean-like classes. In this case at least create javadoc that explains that default constructor should not be used directly.

提交回复
热议问题