Java Reference
In-Depth Information
a parameter is really a local variable.) However, in the case of a parameter of a class
type, the value plugged in is a reference (memory address), and that makes class
parameters behave quite differently from parameters of a primitive type.
Recall that the following makes
variable1
and
variable2
two names for the same
object:
ToyClass variable1 =
new
ToyClass("Joe", 42);
ToyClass variable2;
variable2 = variable1;
So, any change made to
variable2
is, in fact, made to
variable1
. The same thing
happens with parameters of a class type. The parameter is a local variable that is set
equal to the value of its argument. But if its argument is a variable of a class type, this
copies a reference into the parameter. So, the parameter becomes another name for the
argument, and any change made to the object named by the parameter is made to the
object named by the argument, because they are the same object. Thus, a method can
change the instance variables of an object given as an argument. A simple program to
illustrate this is given in Display 5.14. Display 5.15 contains a diagram of the com-
puter's memory as the program in Display 5.14 is executed.
Many programming languages have a parameter passing mechanism known as
call-
by-reference.
If you are familiar with call-by-reference parameters, we should note that
the Java parameter passing mechanism is similar to, but is not exactly the same as, call-
by-reference.
Display 5.14
Parameters of a Class Type
ToyClass
is defined in Display 5.11.
1
public class
ClassParameterDemo
2{
3
public static void
main(String[] args)
4
{
5
ToyClass anObject =
new
ToyClass("Mr. Cellophane", 0);
6
System.out.println(anObject);
7
System.out.println(
8
"Now we call changer with anObject as argument.");
9
ToyClass.changer(anObject);
10
System.out.println(anObject);
Notice that the method
changer
changed the instance variables in the
object
anObject
.
11
}
12
}
Sample Dialogue
Mr. Cellophane 0
Now we call changer with anObject as argument.
Hot Shot 42