References to Objects

As you work with objects, an important thing to understand is the use of 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 the difference, Listing 4.4 shows how references work.

Listing 4.4 The Full Text of ReferencesTest.java
 1: import java.awt.Point; 2: 3: class ReferencesTest { 4: public static void main(String[] arguments) { 5: Point pt1, pt2; 6: pt1 = new Point(100, 100); 7: pt2 = pt1; 8: 9: pt1.x = 200; 10: pt1.y = 200; 11: System.out.println("Point1: ...

Get Sams Teach Yourself Java 2 in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.