References to Objects
As you work with objects, it’s important to understand references. A reference is an address that indicates where an object’s variables and methods are stored.
You aren’t actually using objects when you assign an object to a variable or pass an object to a method as an argument. You aren’t even using copies of the objects. Instead, you’re using references to those objects.
To better illustrate what this means, the RefTester application in Listing 3.4 shows how references work. Create an empty Java file in NetBeans for the class RefTester in the package com.java21days, and enter Listing 3.4 as the application’s source code.
LISTING 3.4 The Full Text of RefTester.java
1: package com.java21days;
2:
3: import java.awt.Point;
4:
5: class RefTester {
6: public static void main(String[] arguments) {
7: Point pt1, pt2;
8: pt1 = new Point(100, 100);
9: pt2 = pt1;
10:
11: pt1.x = 200;
12: pt1.y = 200;
13: System.out.println("Point1: " + pt1.x + ", " + pt1.y);
14: System.out.println("Point2: " + pt2.x + ", " + pt2.y);
15: }
16: }
Save and run the application. The output is shown in Figure 3.4.
FIGURE 3.4 Putting references to a test.
The following takes place in the first part of this program:
- Line 7—Two Point variables are created.
- Line 8—A new Point object is assigned to pt1.
- Line 9—The variable pt1 is assigned to pt2.
Lines 11–14 are the tricky part. The x and y variables of pt1 both are set to 200 and all variables of pt1 and pt2 are displayed onscreen.
You might expect pt1 and pt2 to have different values, but Figure 3.4 shows this not to be the case. The x and y variables of pt2 also have changed even though nothing in the program explicitly changes them. This happens because line 7 creates a reference from pt2 to pt1 instead of creating pt2 as a new object copied from pt1.
The variable pt2 is a reference to the same object as pt1, as shown in Figure 3.5. Either variable can be used to refer to the object or to change its variables.
FIGURE 3.5 References to objects.
If you wanted pt1 and pt2 to refer to separate objects, you could use separate new Point() statements on lines 6–7 to create separate objects, as shown here:
pt1 = new Point(100, 100);
pt2 = new Point(100, 100);
References in Java become particularly important when arguments are passed to methods. You learn more about this later today.