Java Reference
In-Depth Information
};
You will sometimes read in Java topics that Č’numbers are passed by value, objects
are passed by referenceȓ. That is technically not quite correct. In Java, objects
themselves are never passed as parameters; instead, both numbers and object
references are copied by value. To see this clearly, let us consider another
scenario. This method tries to set the otherAccount parameter to a new object:
public class BankAccount
{
public void transfer(double amount, BankAccount
otherAccount)
{
balance = balance - amount;
double newBalance = otherAccount.balance +
amount;
otherAccount = new BankAccount(newBalance); //
Won't work
}
}
In this situation, we are not trying to change the state of the object to which the
parameter variable otherAccount refers; instead, we are trying to replace the
object with a different one (see Modifying an Object Reference Parameter Has No
Effect on the Caller). Now the parameter variable other-Account is replaced
with a reference to a new account. But if you call the method with
harrysChecking.transfer(500, savingsAccount);
then that change does not affect the savingsAccount variable that is supplied
in the call.
In Java, a method can change the state of an object reference parameter, but it
cannot replace the object reference with another.
As you can see, a Java method can update an object's state, but it cannot replace
the contents of an object reference. This shows that object references are passed by
value in Java.
346
Search WWH ::




Custom Search