Java Reference
In-Depth Information
The first line declares minivan as a reference to an object of type Vehicle . Thus, minivan
is a variable that can refer to an object, but it is not an object itself. At this point, minivan
does not refer to an object. The next line creates a new Vehicle object and assigns a refer-
ence to it to minivan . Now, minivan is linked with an object.
Reference Variables and Assignment
In an assignment operation, object reference variables act differently than do variables of
a primitive type, such as int . When you assign one primitive-type variable to another, the
situation is straightforward. The variable on the left receives a copy of the value of the vari-
able on the right. When you assign one object reference variable to another, the situation
is a bit more complicated because you are changing the object that the reference variable
refers to. The effect of this difference can cause some counterintuitive results. For example,
consider the following fragment:
At first glance, it is easy to think that car1 and car2 refer to different objects, but this is not
the case. Instead, car1 and car2 will both refer to the same object. The assignment of car1
to car2 simply makes car2 refer to the same object as does car1 . Thus, the object can be
acted upon by either car1 or car2 . For example, after the assignment
executes, both of these println( ) statements
display the same value: 26.
Although car1 and car2 both refer to the same object, they are not linked in any other
way. For example, a subsequent assignment to car2 simply changes the object to which
car2 refers. For example:
Search WWH ::




Custom Search