Attributes and Methods
A drink that only stores data is half an object. Brew Bar's orders need to do things: add a cup, work out their total, print a receipt. Putting that behaviour inside the class, next to the data it uses, is what makes objects worth having.
The rule
Fields are what an object knows; methods are what it does.
Attributes, usually called fields, hold each object's state. Methods are the actions, and they can read and change that state directly:
public class Order {
String customer;
int cups;
int unitCents;
Order(String customer, int unitCents) {
this.customer = customer;
this.unitCents = unitCents;
this.cups = 1;
}
void addCup() {
cups++;
}
int totalCents() {
return cups * unitCents;
}
String receipt() {
return customer + ": " + cups + " x " + unitCents + " = " + totalCents();
}
}Read a method header from left to right:
- Return type: what the method hands back.
int totalCents()promises an int, and every path through it mustreturnone.voidmeans it hands back nothing. - Name: a verb or question, in camelCase, such as
addCuporisLarge. - Parameters: the inputs in brackets, each with a type.
addCups(int n)would take one;()means none.
Inside a method, a field name such as cups means this object's cups. Methods can also call each other: receipt() uses totalCents() rather than repeating the multiplication.
Calling a method uses a dot on a particular object:
Order o = new Order("Asha", 300);
o.addCup();
System.out.println(o.receipt()); // Asha: 2 x 300 = 600The shortcut
Before writing a method, say its header as a sentence: "Given ___, it gives back ___." The blanks are the parameters and the return type. If the second blank is "nothing, it just changes the order", the return type is void.
Say the sentence
"Given nothing, it gives back nothing; it just lowers the cup count."
Drills
Answer fast — trust the rule.
Order o = new Order("Asha", 300); o.addCup(); o.addCup(); What is o.totalCents()?
What happens with int totalCents() { System.out.println(cups * unitCents); }?
What happens with int n = o.addCup();?
Which header fits "given a number of extra cups, it gives back the new total in cents"?
Remember
- Fields are what an object knows; methods are what it does.
- Say "given ___, it gives back ___" to write the header.
- Traps: forgetting
returnin a non-void method, and using a void result as a value.
