Java Reference
In-Depth Information
When you assign the Employee object to emp (the equal sign in the statement emp = new Employee(); does
this) the main memory address of the Employee object is loaded into the variable emp. (In actuality, a number called
a hash code, which is used by the computer to calculate the memory address, is loaded into emp. For simplicity's
sake, we will refer to this simply as the main memory address.) The address acts as a pointer to the Employee object
(see Figure 5-3 ). This is where the term reference variable comes from. The variable does not contain the object; the
variable references the object.
Figure 5-3.
You may be wondering why Java works like this. Well, complex objects such as Employee require varying
amounts of space. For instance, when an Employee method is executed, new method variables and associated
objects may be created. This means more space must be allocated for the object. In addition, the values assigned to
the variables can be changed. For instance, earlier we changed the city value from Enid to Jacksonville. This type of
change may also require more space for the object. Notice that the space allocated for the variable (which holds the
storage location of the object); however, is a fixed amount.
For instance, the class variables empName and empStreet in Employee are reference variables. When you
created these variables, (i.e., String empName = new String(); ), String objects were also created and assigned
to the variables. A String object contains many methods and private variables. (To verify this, go to the Java online
documentation and look at all the methods that comprise a String .) The String variable (empName) simply points
to the String object (see Figure 5-4 ).
 
Search WWH ::




Custom Search