在Java中将对象作为参数传递

时间:2016-07-09 16:16:59

标签: java

有一个场景

说我有一个班级People&实用程序类PeopleUtil,方法为computeTotalNumberOfPeople

在另一个班级中说EvaluatePeople我有代码

People people = new People();
people.setValue(10);
people.setX(45);
PeopleUtil.computeTotalNumberOfPeople(people);
this.persistPeople(people);

computeTotalNumberOfPeople方法

public void computeTotalNumberOfPeople(People people){
  //logic for computing total no of people & then
  int totalPeople = certainIntValue; 
  // I can return the totalPeople value from this method but I am not doing it just for the sake of this scenario
  people.setTotalNumberOfPeople(totalPeople);
}

当我查看db行中的People对象时,我看到totalNumberOfPeople值仍然存在。这其实很好。

我的问题是,我对它有点困惑,不应该computeTotalNumberOfPeople方法将具有额外设定值的人物对象返回给方法调用者代码&那么该对象应该作为参数传递给peristPeople方法吗?

我希望你理解我的意思,它似乎并不正确

1 个答案:

答案 0 :(得分:2)

对象是可变的 - 它们可以被更改。

因此,当您致电people.setTotalNumberOfPeople(totalPeople)时,您要将totalNumberOfPeople变量(或People类内所谓的变量)设置为totalPeople people对象

当您退出computeTotalNumberOfPeople方法时,该对象仍然是被修改的对象 - 该方法的更改仍然存在。

考虑它的一种方法是将引用传递给people。当您致电computeTotalNumberOfPeople(people)时,您正在将参考传递给people。修改people后,您修改内存中的相同位置,因此更改仍然存在。