College Board Unit 3
How it works
A class defines instance variables that hold each object's state and constructors that initialize them. A constructor has the same name as the class and no return type, and it typically assigns its parameters into the instance variables. When a parameter shares a name with an instance variable, the parameter shadows it, and this.field = field; is what distinguishes the two. Instance variables not assigned in a constructor keep their type defaults.
Initialise every field in every constructor, so no object begins in a half-built state.
Common error
Writing a return type on a constructor, which turns it into an ordinary method that is never called.
Worked example
Java
class Ticket {
private int remaining;
public Ticket(int count) { remaining = count; }
public void use() { remaining--; }
public int getRemaining() { return remaining; }
}
Ticket a = new Ticket(3);
Ticket b = new Ticket(3);
a.use();
System.out.println(a.getRemaining() + ":" + b.getRemaining());Output
2:3Each constructor call initializes a separate object. Calling use on a changes only a's instance field.
Exercises
7.3.1 · Trace
Determine the exact output. Explain the Java rule or state changes that produce it.
Java
int[] a = new int[2];
int[] b = new int[2];
a[0] = 6;
System.out.println(a[0] + ":" + b[0]);Show solution
Output
6:0Each new expression creates a distinct object with independent storage.
7.3.2 · Write code
Write a Counter class with a private int value, a constructor accepting its initial value, increment(), and getValue(). The methods operate on instance state.
Show solution
One valid solution is shown below. Other implementations satisfying the contract are also valid.
Java
public class Counter {
private int value;
public Counter(int initial) { value = initial; }
public void increment() { value++; }
public int getValue() { return value; }
}Check your code
Java
Counter a = new Counter(2); Counter b = new Counter(10);
a.increment();
System.out.println(a.getValue() + ":" + b.getValue());Expected output
3:10