Tuesday, June 9, 2015

Java - Pass Object by Reference

Facts:
  • Java passes everything by value.
  • References to objects-as well.
  • As long as you use or modify the object whose reference you've got in a parm, you're good.
  • When you want to assign a new object to replace the one that was passed-in, you're for a bad surprise.  Doesn't work
  • The above case can be hidden:
private MainReturnObject getThatObject(BigDecimal extraValue) {
  ...
  extraValue = extraValue.add(BigDecimal.valueOf(7));
  ...
}
...
BigDecimal objectExtraValue;
anObject = getThatObject(objectExtraValue);

After your program exits from getThatObject(), you'll find that extraValue = 0.0.  The method has modified the getThatObject's copy of the reference to objectExtraValue.

No comments: