-1

A friend of mine wrote such code:

public AccountModel updateAccountPotential(Long accId) {

    AccountModel accModel = accountDAO.findById(accId);

    this.calculatePotential(accModel);
    return accountDAO.save(accModel);
}

private void calculatePotential(AccountModel accModel) {
    accModel.setPotential(some formula);
}

There's this method calculatePotential that returns nothing, but does some operations on parameter's field. Will that affect the original object in updateAccountPotential method?

Maciaz
  • 1,084
  • 1
  • 16
  • 31
  • 2
    **Yes**, because https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value . – luk2302 Aug 07 '18 at 08:16
  • It would be nice to see the AccountModel::setPotencial method, but I guess is a "typical" setter so, yes, original object will be affected – Héctor Aug 07 '18 at 08:16
  • `accModel.setPotential(some formula);` will definitely affect the `accModel`... – deHaar Aug 07 '18 at 08:16
  • Yes this is perfectly valid code and will affect the object as long as `setPotential` actually does something to the object that is – Popeye Aug 07 '18 at 08:16
  • If by "original object" you refer to the object for which the `updateAccountPotential` was called, `this.calculatePotential(accModel)` will probably **not** modify that object, since it is likely to modify just the `AccountModel ` instance. – Eran Aug 07 '18 at 08:19
  • 1
    You could just check it through `accModel.getPotential()` after line `this.calculatePotential(accModel);` rather than asking – Shubhendu Pramanik Aug 07 '18 at 08:19

1 Answers1

1

Yes, assuming setPotential is a typical setter, because the value passed into updateAccountPotential is a reference to the object. That method modifies the object's state (via setPotential) (presumably). It's exactly as though you did this:

AccountModel a = /*...get the account model...*/;
AccountModel b = a;
b.setPotential(/*...*/);
// Both `b` and `a` refer to the same object, and so the state of that object
// is visible whether you go through `b` or `a` to get to it
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875