Card 02/ 09

ExampleDifficulty: Beginner1 min

One Order Class, Three Orders

Three objects made from one class, and one of them cancelled. Watch which values move and which stay put.

java
Order a = new Order();
a.customer = "Ada";

Order b = new Order();
b.customer = "Grace";

Order c = a;

a.cancel();

System.out.println(a.status + " " + b.status + " " + c.status);
text
cancelled open cancelled

b is untouched, because it is a different object with its own status. c changed, because line 7 did not make a third order — it copied an address, so a and c are two names for one object.

Three variables, and how many objects there actually are
VariablePoints atOwn status
aThe first orderShared with c
bThe second orderIts own
cThe first orderShared with a

What to notice: new is the only thing in Java that creates an object. Every other line moves addresses around, which is why counting the new keywords tells you how many objects exist.