What is the best practice to modify an object passed to a method

后端 未结 2 899
我在风中等你
我在风中等你 2020-12-16 16:23

After passing an object into a method, I would like to change one of its fields. What\'s the best practice to do this task in Java?

2条回答
  •  庸人自扰
    2020-12-16 16:52

    Be aware of the fact that even if the object is passed as final it still can be changed. You just can't reassign the variable, which normally is desired for an (input/)output parameter.

    Taking Jigar Joshis example:

    public void increasePersonAgeByOneMonth(final Person p ){
      p = new Person(); //this won't work, which is ok since otherwise the parameter itself would not be changed by the next method
      p.setAge(((p.getAge()*12.0) + 1)/12.0); //ok
    }
    

提交回复
热议问题