JAVA / CHAPTER 04
Classes
IntermediateDefine state, constructors, and instance methods for a small object.
By the end of this chapter
- Declare private instance fields
- Initialize an object in a constructor
- Trace independent object state
The idea
A class defines a kind of object by grouping state and behavior. Instance fields belong to individual objects, so two counters can retain different totals. A constructor establishes the initial state when new creates an instance. The constructor has the class name and no return type. An instance method works with the receiver object, which is the expression before the dot at the call site.
Keep fields private and expose a small set of operations. This makes it possible to change the representation later while callers continue to use the same methods. Parameters are local names for supplied arguments; this can distinguish an instance field from a parameter with the same name.
class Counter {
private int value;
Counter(int value) { this.value = value; }
void add(int amount) { value += amount; }
int getValue() { return value; }
}
public class Main {
public static void main(String[] args) {
Counter a = new Counter(2);
Counter b = new Counter(8);
a.add(3);
System.out.println(a.getValue() + ":" + b.getValue());
}
}5:8
The constructor initializes each receiver independently. Calling add on a changes only the field stored in that object.
Try it yourself
Design a Lamp with private on state, a toggle method, and an isOn query.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING