This example is taken from the Java programming book; 4th Edition.
After stumbling upon this code example I am mystified at why it still prints out the new reference to the object, even though we declared it to be ‘null’. In theory, we’re altering the references to the object which is shared between the whole program, though we initialize the object to null in the commonName method. At the point of the flow of control at commonName, the field in the body constructor is initialized to “Sirius”; when we alter the references to the object (In Java you call-by-value) the field is changed to Dog Star. The last line of the method we set the whole object to null, once we print out the object the runtime should greet us with a null references.
The only way to get round this is by setting the commonName method as final. Can any Java guru explain why this happens, especially in any call-by-value language.
class PassRef
{
public static void main (String[] args) {
Body sirius = new Body ("Sirus", 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;
}
}
The output:
before: 0 (Sirius)
after: 0 (Dog Star)
You’re mystified only because you don’t understand what pass by value means.
The common method cannot alter the reference that it’s passed. That’s why null is ignored and you print the new value.
You can alter the state of the object that the passed reference points to, but you cannot change the value of the reference itself.