TOPIC 3.4 · STUDY
Constructors
An object's state is the current values of its attributes. A constructor shares the class name, has no return type, and sets that initial state. new picks the overload whose parameter types match, and a written constructor replaces the free default no-arg form.
3.4.A
Constructors and initial state
An object's state is the current values of its attributes. A Loaf has-a weight and has-a crust flag. Those fields are the state. The Loaf class is the type of the object; it is not an attribute of itself.
A constructor sets that initial state when the object is created. It uses the class name, has no return type, and copies parameters into the instance fields. The expression new ClassName(args) creates the object, runs the constructor whose parameter types match the arguments, and yields a reference to the new object.
public class Parcel {
private int grams;
private boolean sealed;
public Parcel(int weight, boolean closed) {
grams = weight;
sealed = closed;
}
public String dump() {
return grams + ":" + sealed;
}
}
Parcel box = new Parcel(40, true);
System.out.print(box.dump());
new Parcel(40, true) selects Parcel(int, boolean). The constructor stores 40 in grams and true in sealed, so dump prints 40:true. Matching is by type and order: the call must line up with a written constructor.
The two arguments become the object's starting field values after the matching constructor runs.
If you write no constructor at all, Java supplies a default no-argument constructor. Fields then keep type defaults: int is 0, double is 0.0, boolean is false, and a reference type such as String is null. As soon as you write any constructor, that free default disappears. new Parcel() would not compile for the class above unless you also add an explicit Parcel() overload. Overloading means writing more than one constructor with different parameter-type lists so each new call can match one of them.
When a constructor parameter is a mutable object and the class must keep its own copy, do not store the caller's reference. Build a new object from the needed value instead. For example, minutes = new Dial(start.getTicks()) gives the field its own Dial. Assigning minutes = start would alias the caller, so later changes through the original variable would rewrite the constructed object's state as well.
Key points
- State is the current values of an object's attributes; the class is the type, not one of those attributes.
- A constructor has the class name, no return type, and sets the initial field values.
- new ClassName(args) runs the constructor whose parameter types match the arguments.
- With no written constructor, Java supplies a default; fields start at 0, 0.0, false, or null.
- Writing any constructor removes the free default no-arg form unless you add one yourself.
- For a mutable parameter that must not be shared, construct a new object instead of storing the caller's reference.
A constructor has no return type, not even void.