Card 02/ 09
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:
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);cancelled open cancelledb 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.
| Variable | Points at | Own status |
|---|---|---|
a | The first order | Shared with c |
b | The second order | Its own |
c | The first order | Shared 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.
← → move through sections and cards