English
this is a reference to the current object 当前对象. Use it to tell a field apart from a parameter with the same name, or to call another method of the same object:
public Student(String name, int score) {
this.name = name; // this.name is the field; name is the parameter
this.score = score;
}
Exam skill: when a constructor or setter's parameter has the same name as a field, write this.field = field to distinguish the field from the parameter; field = field assigns the parameter to itself.
Writing a complete class
Free-response question 2 usually asks you to write a whole class, given a table of example calls. The method is always the same. Here is a new example in that style.
A PunchCard records stamps at a coffee shop. Each time a customer has collected the needed number of stamps, the stamps reset to 0 and the customer earns one free drink.
| Statement |
Result |
PunchCard c = new PunchCard(3); |
3 stamps are needed for each free drink |
c.redeem(); |
returns false: no free drink yet |
c.stamp(); c.stamp(); |
no return value |
c.status(); |
returns "2/3, free: 0" |
c.stamp(); |
the third stamp: stamps reset, one free drink earned |
c.status(); |
returns "0/3, free: 1" |
c.redeem(); |
returns true, and uses the free drink |
c.redeem(); |
returns false |
Step 1: find the state. Ask what the object must remember between calls. Here it needs three things: how many stamps are needed, how many it has, and how many free drinks are waiting. These become private instance variables. A value used only inside one method stays a local variable.
Step 2: write the headers from the table. The call c.status() is used for its value, so it returns a String; c.stamp(); gives nothing back, so it is void.
Step 3: fill in the bodies, one row at a time.
public class PunchCard
{
private int needed;
private int stamps;
private int freeDrinks;
public PunchCard(int n)
{
needed = n;
stamps = 0;
freeDrinks = 0;
}
public void stamp()
{
stamps++;
if (stamps == needed)
{
stamps = 0;
freeDrinks++;
}
}
public boolean redeem()
{
if (freeDrinks > 0)
{
freeDrinks--;
return true;
}
return false;
}
public String status()
{
return stamps + "/" + needed + ", free: " + freeDrinks;
}
}
Step 4: trace the table. Follow each row with the three variables. After the three stamps they hold 3, 0 and 1, so status() gives "0/3, free: 1", which matches.
Common mistakes.
- Using
System.out.println in status(). The table says returns, so write return.
- Writing
int stamps = 0; inside the constructor. This makes a new local variable, and the instance variable is not set by that line.
- Making instance variables
public, or static. Each card must keep its own count.
- Keeping the method's parameter
n and not storing it. It is gone when the constructor ends, so stamp() cannot use it.
- Writing
redeem() so that it returns true without reducing freeDrinks. The method has a side effect that the table shows in its last row.