Card 02/ 09

ExampleDifficulty: Beginner1 min

Classes Example: One Order Class, Three Variables, Two Objects

One order cancelled, and a second variable that turns out to be cancelled too.

Each new creates one object with its own fields, the variables each object carries, and assigning one variable to another only copies the address, which says where the object lives in memory. Three variables made from one class, and one of them cancelled:

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

Notice that 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.