Does Java bean's setter permit return this?

后端 未结 10 598
一向
一向 2020-12-06 10:02

can I define setter method to return this rather than void?

Like:

ClassA setItem1() {
      return this;
}

ClassA setItem2() {
      return this;
}
         


        
10条回答
  •  孤街浪徒
    2020-12-06 10:53

    No reason you couldn't do that. Personally, if the setters are being used during object creation, I'd name them withItem1() and withItem2().

    ClassA obj = new ClassA().withItem1(item1).withItem2(item2);
    

    Makes it a bit clearer (to me anyway) what the intent of the methods are.

提交回复
热议问题