Classes and Objects
A class describes the fields every object of its kind has, and each use of new with a constructor creates a separate object with its own copy of those fields.
Create independent instances and distinguish shared behavior from per-object state.
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.