Complete the Primitive types vs references exercises before reviewing the solutions.
Review the reference exercise 1 solution with AP CS Tutor Brandon Horn.
Original code
Coordinate2D referenceOne = new Coordinate2D(1, 1);
Coordinate2D referenceTwo = new Coordinate2D(2, 2);
System.out.println(referenceOne);
System.out.println(referenceTwo);
Output
(1, 1)
(2, 2)
Step by step with memory diagrams
Step 1
Coordinate2D referenceOne = new Coordinate2D(1, 1);
Memory diagram after Step 1
The right side of an assignment statement is evaluated first. new Coordinate2D(1, 1);
instantiates the Coordinate2D
class (makes an object/instance of the class). Each object/instance of type Coordinate2D
gets its own copy of the instance variables (x
and y
).
Creating an object/instance of a class runs one of the class’s constructors. Since 2 int
arguments are passed, the constructor that accepts 2 int
parameters is run. The constructor sets both instance variables to 1
. The constructor returns the memory address of the newly created object.
The left side of this assignment statement, Coordinate2D referenceOne
, makes a variable/reference of type Coordinate2D
. The variable/reference stores the memory location of the object that was created on the right side. It is common to say that the variable points to the object.
The value of referenceOne
is not the object (the box) and it is definitely not the values of the instance variables (x: 1, y: 1
). The value of referenceOne
is the memory address of the object containing x: 1, y: 1
. I like to think of the value of referenceOne
as the arrow.
See Constructing objects for more.
Step 2
Coordinate2D referenceOne = new Coordinate2D(1, 1);
Coordinate2D referenceTwo = new Coordinate2D(2, 2);
Memory diagram after Step 2
referenceOne
points to (stores the memory address of) the object containing (1, 1)
. referenceTwo
points to (stores the memory address of) the object containing (2, 2)
.
Step 3
Coordinate2D referenceOne = new Coordinate2D(1, 1);
Coordinate2D referenceTwo = new Coordinate2D(2, 2);
System.out.println(referenceOne);
System.out.println(referenceTwo);
Memory diagram after Step 3
Output after Step 3
(1, 1)
(2, 2)
When referenceOne
is printed, Java checks if referenceOne
points to an object. referenceOne
does point to an object. Java automatically runs the toString
method on the object to which referenceOne
points. The Coordinate2D toString
method returns a String
in the form (x, y)
.
The same process is followed when referenceTwo
is printed.