THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

without affecting the reference that was passed. But if you change any fields of the object or invoke methods
that change the object's state, the object is changed for every part of the program that holds a reference to it.
Here is an example to show this distinction:


class PassRef {
public static void main(String[] args) {
Body sirius = new Body("Sirius", null);


System.out.println("before: " + sirius);
commonName(sirius);
System.out.println("after: " + sirius);
}


public static void commonName(Body bodyRef) {
bodyRef.name = "Dog Star";
bodyRef = null;
}
}


This program produces the following output:


before: 0 (Sirius)
after: 0 (Dog Star)


Notice that the contents of the object have been modified with a name change, while the variable sirius
still refers to the Body object even though the method commonName changed the value of its bodyRef
parameter variable to null. This requires some explanation.


The following diagram shows the state of the variables just after main invokes commonName:


At this point, the two variables sirius (in main) and bodyRef (in commonName) both refer to the same
underlying object. When commonName changes the field bodyRef.name, the name is changed in the
underlying object that the two variables share. When commonName changes the value of bodyRef to null,
only the value of the bodyRef variable is changed; the value of sirius remains unchanged because the
parameter bodyRef is a pass-by-value copy of sirius. Inside the method commonName, all you are
changing is the value in the parameter variable bodyRef, just as all you changed in halveIt was the value
in the parameter variable arg. If changing bodyRef affected the value of sirius in main, the "after" line
would say "null". However, the variable bodyRef in commonName and the variable sirius in main
both refer to the same underlying object, so the change made inside commonName is visible through the
reference sirius.


Some people will say incorrectly that objects are passed "by reference." In programming language design, the
term pass by reference properly means that when an argument is passed to a function, the invoked function
gets a reference to the original value, not a copy of its value. If the function modifies its parameter, the value
in the calling code will be changed because the argument and parameter use the same slot in memory. If the
Java programming language actually had pass-by-reference parameters, there would be a way to declare

Free download pdf