Attributes and Methods
Fields store each object's state and methods act on that state, with the header stating the parameters a method takes and the type of value it returns.
Trace a method call as it reads or changes an object's fields.
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 = 600