Search

Friday, December 14, 2018

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 variable on the right. When you assign an 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 counter intuitive results. For example,consider the following fragment:

Vehicle car1 = new Vehicle();
Vehicle car2 = car1;
At first glance, it is easy to think that car 1 and car 2 refer to different objects, but this is not the case. Instead, car 1 and car 2 will both refer to the same object. The assignment of car 1 to car 2 simply makes car 2 refer to the same object as does car 1. Thus, the object can be acted upon by either car 1 or car 2. For example, after the assignment
car 1. mpg = 26;
executes, both of the seprintln( )statements
System.out.println(car1.mpg);
System.out.println(car2.mpg);
display the same value: 26. Although car 1 and car 2 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment to car 2 simply changes the object to which car 2 refers. For example:
Vehicle car1 = new Vehicle();
Vehicle car2 = car1;
Vehicle car3 = new Vehicle();
car2 = car3;
// now car2 and car3 refer to the same object.
After this sequence executes, car 2 refers to the same object as car 3. The object referred to by car 1 is unchanged.



0 comments:

Post a Comment