Classes and Objects
So far Brew Bar's drinks have been loose variables: a name here, a price there. With twenty drinks that turns into forty variables and plenty of mix-ups. Java's answer, and the idea the whole language is built around, is to bundle each drink's data into one object made from a class.
The rule
A class is the recipe; each
newmakes a separate object.
A class describes what every object of its kind holds. A constructor, which has the class's name and no return type, sets up each new object:
public class Drink {
String name;
int priceCents;
Drink(String name, int priceCents) {
this.name = name;
this.priceCents = priceCents;
}
}An object is one real instance, created with new:
Drink latte = new Drink("Latte", 300);
Drink mocha = new Drink("Mocha", 340);
System.out.println(latte.name); // Latte
mocha.priceCents = 350; // changes the mocha onlyWhat to notice:
- Each object has its own fields. Changing
mocha.priceCentsleaveslatteuntouched. thismeans "the object being built or used". In the constructor,this.nameis the field and plainnameis the parameter.- A class variable holds a reference, like an array variable.
Drink favourite = latte;makes a second name for the same object; it does not create a new drink. - Unset fields get defaults:
0for numbers,falsefor booleans,nullfor references such asString. (Only local variables are left without a default.) - Writing any constructor removes the free one. If you do not write a constructor, Java supplies an empty one that takes no arguments. Once you write
Drink(String, int),new Drink()no longer compiles unless you add it yourself.
The shortcut
Count new, not variables. Every new is exactly one object; every = between two reference variables is just another label on an existing one.
First line
Drink a = new Drink("Latte", 300);Onenew: one object.
Drills
Answer fast — trust the rule.
After those three lines, what does b.priceCents = 280; System.out.println(a.priceCents); print?
The class has only the constructor Drink(String name, int priceCents). What does new Drink() do?
A class Cup has a field int sizeMl; that no constructor sets. What is it in a new Cup?
In the constructor, what would name = name; (without this.) do?
Remember
- A class is the recipe; each
newmakes a separate object with its own fields. - Count
newto count objects;=between references only adds a label. - Traps: the vanished no-argument constructor, and forgetting
this.when names match.
