Java Reference
In-Depth Information
Let's take a look at some examples that declare and initialize reference types. Suppose
we declare a reference of type java.util.Date and a reference of type String :
java.util.Date today;
String greeting;
The today variable is a reference of type Date and can only point to a Date object. The
greeting variable is a reference that can only point to a String object. A value is assigned
to a reference in one of two ways:
A reference can be assigned to another reference of the same type.
A reference can be assigned to a new object using the new keyword.
For example, the following statements assign these references to new objects:
today = new java.util.Date();
greeting = “How are you?”;
The today reference now points to a new Date object in memory, and today can be
used to access the various fi elds and methods of this Date object. Similarly, the greeting
reference points to a new String object, “How are you?” The String and Date objects
do not have names and can only be accessed via their corresponding reference. Figure 1.6
shows how the reference types appear in memory.
FIGURE 1.6
An object in memory can only be accessed via a reference.
A Date object
A Date reference
today
day
29
month
7
year
2011
A String reference
greeting
A String object
How are you?
Search WWH ::




Custom Search