The Analogy: The Commissioning Sheet For A New Lift
A lift is bolted into its shaft, wired, and physically complete for days before anyone is allowed to ride it. What stands between "installed" and "in service" is a commissioning sheet: load test at a hundred and twenty-five percent of the rated weight, door dwell time, brake drop test, overspeed governor trip, emergency lowering. An engineer works down the sheet once, in order, and signs each line. Until the last signature is on the paper, the car is locked out at the landing. The sheet does not build the lift -- the lift already exists, steel and cable and motor. The sheet is what makes it fit to use.
That once-only, before-anyone-rides-it position is the whole reason the sheet can promise anything. "The brake holds the rated load" is a fact about this specific lift for the whole of its service life, and it is a fact only because one particular line on one particular sheet was completed before the first passenger stepped in. There is no way to add that guarantee afterwards to a lift already carrying people; you would have to take it out of service, which is to say, stop being a lift for a while. Anything you want to be true of a lift for its whole life has to be established here or not at all.
There is more than one sheet, and the sheets know about each other. A goods lift and a passenger lift in the same building get different sheets because the questions genuinely differ -- one cares about pallet loading, the other about door reopening on obstruction. But they are not independent documents. The passenger sheet's first line reads "complete the common hoistway sheet, then continue below", so the shared checks live in exactly one place and cannot drift out of step between the two. And in every case the hoistway, machine room and hoist are commissioned before the car itself. You cannot load-test a car hanging in a shaft nobody has proved.
The failure mode is an engineer trying to save a morning. He starts the lift's automatic self-diagnostic while the door-sensor loom is still half-terminated. The diagnostic is a good routine and it does exactly what it was written to do: it asks the door subsystem for its configured dwell time. The subsystem answers, because it is powered -- it answers zero, because nobody has set it yet. The diagnostic records zero, reports a pass, and the line gets signed. Nothing malfunctioned. The only mistake was running a check that consults a subsystem during the window in which subsystems are still being wired. The quieter version of the same problem is a sheet handed over with a line left blank, because a blank line and a line that passed silently look identical a year later.
Syntax or Core Structure
A constructor has the class's exact name, no return type at all, and runs once when new creates an object. Its job is to leave the object in a state that is valid, and the strongest version of that job is to make an invalid one impossible to produce.
public class Lift {
private final String shaft;
private final int capacityKg;
private int floor;
private boolean inService;
// The full constructor: validates first, then assigns.
Lift(String shaft, int capacityKg, int floor) {
if (capacityKg <= 0) {
throw new IllegalArgumentException("capacityKg must be positive: " + capacityKg);
}
this.shaft = shaft;
this.capacityKg = capacityKg;
this.floor = floor;
this.inService = true;
}
// A convenience constructor: delegates with this(...), duplicates nothing.
Lift(String shaft, int capacityKg) {
this(shaft, capacityKg, 0);
}
String shaft() { return shaft; }
int capacityKg() { return capacityKg; }
int floor() { return floor; }
boolean inService() { return inService; }
public static void main(String[] args) {
Lift a = new Lift("A", 1600, 3);
Lift b = new Lift("B", 800);
System.out.println("a shaft " + a.shaft());
System.out.println("a floor " + a.floor());
System.out.println("b floor " + b.floor());
System.out.println("b cap " + b.capacityKg());
System.out.println("b service " + b.inService());
boolean rejected = false;
try {
new Lift("C", 0);
} catch (IllegalArgumentException e) {
rejected = true;
}
System.out.println("rejected " + rejected);
}
}
Output:
a shaft A
a floor 3
b floor 0
b cap 800
b service true
rejected true
The two constructors are the same constructor with different amounts of information supplied. Lift("B", 800) did not repeat the validation or the assignments; it called the three-argument version with floor fixed at 0, which is why b floor reads 0 and why adding a fifth field later means editing exactly one body. Only one of these two constructors ever assigns a field, and that is the arrangement to aim for.
The rejection is the point of the whole method. new Lift("C", 0) went through the short constructor into the long one, failed the capacity check, and threw before a single field was assigned. There is no half-built Lift with a capacity of zero sitting anywhere -- the reference was never handed back, so nothing in the program can hold one. Every method on Lift may now assume capacityKg is positive without re-checking, and that assumption is safe for the object's whole life.
Note what the constructor is not. It has no return type, not even void, and return capacityKg; inside it is a compile error -- though a bare return; is legal and simply ends it early. It does not create the object either: new allocates the memory and zeroes every field, and the constructor is handed that blank object to fill in. That distinction stops being pedantic in a moment.
Technical Depth: What The Compiler Writes For You, In What Order The Pieces Run, And Why A Constructor Must Never Call An Overridable Method
A constructor is not a method, and the differences are load-bearing
It is tempting to file constructors under "methods with a funny name". Almost every rule is different, and one of those differences is responsible for a bug that compiles cleanly and produces no warning.
| Property | An ordinary method | A constructor |
|---|---|---|
| Return type | Required, possibly void | None at all, not even void |
| Name | Any legal identifier | Exactly the class name |
| Inherited by a subclass | Yes | No -- never |
Can be static | Yes | No |
Can be abstract, final or synchronized | Yes | No |
| How it is invoked | By name, on an object or a class | Only by new, this(...) or super(...) |
| Can be overloaded | Yes | Yes |
Can be private | Yes | Yes, and that is how you forbid new |
The bug is the first row. public void Lift(String shaft) { ... } is a perfectly legal method that happens to be named Lift, and it will never run when you write new Lift("A"). Instead the compiler-supplied no-arg constructor runs, every field keeps its zero value, and the only symptom is that the object is empty. No error, no warning, and the offending line looks correct at a glance.
The no-arg constructor is a gift that is withdrawn the moment you write your own
If a class declares no constructor at all, the compiler inserts one: no parameters, the same access level as the class, and a body consisting of nothing but an implicit super(). This is why new ArrayList<>() works for classes you have not written a constructor for.
Declare any constructor -- one parameter, five, private, it makes no difference -- and that inserted constructor is not generated. new Lift() above does not compile, and nothing tells you it used to. Adding a no-arg constructor back is a deliberate decision, and for a class with final fields it forces you to answer a real question: what does a Lift with no shaft and no capacity actually mean? Usually the honest answer is "nothing", and the right move is to leave it uncompilable.
The same rule bites through inheritance. A subclass constructor that does not start with an explicit this(...) or super(...) gets an implicit super() -- and if the superclass has no no-arg constructor, that implicit call has nothing to bind to. The error names the superclass, which sends people looking in the wrong file; the fix is always an explicit super(...) in the subclass.
The order is fixed, and you can watch it
public class Order {
private static int step;
static int note(String what) {
step++;
System.out.println("step " + step + " " + what);
return 0;
}
static class Base {
int baseField = note("Base field initialiser");
Base() {
note("Base constructor body");
}
}
static class Derived extends Base {
int derivedField = note("Derived field initialiser");
Derived() {
super();
note("Derived constructor body");
}
}
public static void main(String[] args) {
new Derived();
System.out.println("steps " + step);
}
}
Output:
step 1 Base field initialiser
step 2 Base constructor body
step 3 Derived field initialiser
step 4 Derived constructor body
steps 4
The superclass is finished before the subclass starts, and within each class the field initialisers run before the constructor body. That ordering is not a convention, it is a guarantee.
| Step | What happens | Worth knowing |
|---|---|---|
| 1 | new allocates the object and sets every field to its type's zero value | 0, false, 0.0, null -- before any code of yours runs |
| 2 | The explicit or implicit super(...) runs, initialising the superclass completely | Recurses up to Object before coming back down |
| 3 | This class's instance field initialisers and instance initialiser blocks run | In source order, interleaved with each other |
| 4 | The rest of this constructor's body runs | The first point at which the whole object is coherent |
A this(...) call changes the picture in one important way: it delegates to another constructor of the same class, which performs steps 2 and 3, and only then does the delegating constructor's own body run. Field initialisers therefore execute exactly once per object no matter how many constructors the chain passes through -- which is another reason to have one constructor that does the work and the rest delegate to it.
A blank final field must be assigned exactly once, on every path
A final field with no initialiser is a blank final, and the compiler tracks it: every constructor must assign it exactly once before finishing normally, and no constructor may assign it twice. Both halves are checked, and a path that throws is not "finishing normally", which is why validating before assigning is legal.
This is the strongest tool in the language for making a class impossible to misuse, because it converts "remember to set the shaft" from a discipline into a build error. It is also why final and constructors are usually discussed together: final fields give you exactly one chance to get the object right, and the constructor is that chance.
What final does not do is make the object immutable. private final List<String> extras guarantees that extras always refers to the same list; it says nothing about what is in the list, and the Real World Example below turns on that distinction.
Never call an overridable method from a constructor
This is the analogy's half-wired door sensor, and it is worth seeing rather than being told.
public class Trap {
static class Report {
private final int width;
Report(int width) {
this.width = width;
render(); // dynamic dispatch, from a constructor
}
void render() {
System.out.println("base width " + width);
}
}
static class Boxed extends Report {
private final String edge;
Boxed(int width, String edge) {
super(width); // render() runs inside here
this.edge = edge;
}
@Override
void render() {
System.out.println("during edge " + edge);
}
}
public static void main(String[] args) {
Boxed b = new Boxed(40, "solid");
b.render();
}
}
Output:
during edge null
during edge solid
Report.render never ran. The call inside Report's constructor dispatched on the object's actual class, which is Boxed, so Boxed.render executed while Boxed's own constructor had not yet reached this.edge = edge. Read the two output lines together: edge is final, it is read twice, and it gives two different answers. That is not a bug in the JVM -- step 2 of the table above completes before step 4, and super(width) is step 2.
The rule that follows is absolute in practice: a constructor may only call methods that cannot be overridden. Make the helper private, static or final, or move the call out of the constructor entirely into a static factory that constructs the object first and then calls the method on the finished result.
Real World Example: A Booking That Cannot Be Constructed In An Invalid State
A hotel reservation is a good subject because the rules are unglamorous and absolute: a booking has a code, it covers at least one night and no more than four weeks, it has at least one guest. If those hold for every Reservation object that exists, no method anywhere downstream has to check them again. The constructor is the only place that guarantee can be installed.
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class Reservation {
static final int MAX_NIGHTS = 28;
private static final List<String> LEDGER = new ArrayList<>();
private final String code;
private final int nights;
private final int guests;
private final int ratePence; // per night
private final List<String> extras;
Reservation(String code, int nights, int guests, int ratePence, List<String> extras) {
if (code == null || code.isEmpty()) {
throw new IllegalArgumentException("code must not be blank");
}
if (nights < 1 || nights > MAX_NIGHTS) {
throw new IllegalArgumentException("nights out of range: " + nights);
}
if (guests < 1) {
throw new IllegalArgumentException("guests must be at least 1: " + guests);
}
this.code = code;
this.nights = nights;
this.guests = guests;
this.ratePence = ratePence;
this.extras = new ArrayList<>(extras); // defensive copy on the way in
LEDGER.add(code); // the design flaw -- see below
}
Reservation(String code, int nights) {
this(code, nights, 1, 9000, new ArrayList<>());
}
int totalPence() {
return nights * ratePence + extras.size() * 500;
}
List<String> extras() {
return List.copyOf(extras); // and on the way out
}
String code() { return code; }
int nights() { return nights; }
int guests() { return guests; }
static int ledgerSize() {
return LEDGER.size();
}
public static void main(String[] args) {
List<String> caller = new ArrayList<>();
caller.add("parking");
caller.add("breakfast");
Reservation r1 = new Reservation("R-1001", 3, 2, 11000, caller);
Reservation r2 = new Reservation("R-1002", 1);
caller.add("late-checkout"); // must not reach r1
List<Reservation> all = new ArrayList<>();
all.add(r1);
all.add(r2);
for (Reservation r : all) {
System.out.println(String.format(Locale.ROOT,
"%-7s nights %2d guests %d extras %d total %6d",
r.code(), r.nights(), r.guests(), r.extras().size(), r.totalPence()));
}
System.out.println("caller " + caller.size());
System.out.println("r1 extras " + r1.extras().size());
boolean frozen = false;
try {
r1.extras().add("spa");
} catch (UnsupportedOperationException e) {
frozen = true;
}
System.out.println("frozen " + frozen);
int rejected = 0;
try {
new Reservation("R-1003", 0, 1, 9000, caller);
} catch (IllegalArgumentException e) {
rejected++;
}
try {
new Reservation("", 2, 1, 9000, caller);
} catch (IllegalArgumentException e) {
rejected++;
}
try {
new Reservation("R-1004", 40, 1, 9000, caller);
} catch (IllegalArgumentException e) {
rejected++;
}
System.out.println("rejected " + rejected);
System.out.println("ledger " + Reservation.ledgerSize());
System.out.println("max " + MAX_NIGHTS);
}
}
Output:
R-1001 nights 3 guests 2 extras 2 total 34000
R-1002 nights 1 guests 1 extras 0 total 9000
caller 3
r1 extras 2
frozen true
rejected 3
ledger 2
max 28
What the constructor buys is stated by the rejected 3 line. Three attempts to create a nonsense booking -- zero nights, a blank code, forty nights -- and none of them produced an object. Not a flagged object, not an object with an isValid() method returning false: no object at all, because new threw before returning a reference and nothing in the program can hold one. That is what makes the three rules invariants rather than hopes. totalPence() can multiply nights without wondering whether it might be zero, and a report can print guests without a defensive check, because the only door into this class was locked behind a validation.
The delegation and the copy are the other two decisions worth reading. Reservation(String, int) repeats no validation and assigns no field; it calls the five-argument version with sensible defaults, so all five final fields are still assigned in exactly one body. And the defensive copy earns its place three lines later: caller gained late-checkout after r1 was built, caller 3 confirms the caller's list grew, and r1 extras 2 confirms the reservation did not. Without new ArrayList<>(extras) those two numbers would both read 3, and final would not have saved it -- final promises that extras always points at the same list, not that the list stops changing.
frozen true closes the other half of the boundary. Copying on the way in stops the caller mutating the object's state; returning List.copyOf on the way out stops the caller mutating it through a getter. A class that does one and not the other is only half sealed, and the half that is missing is the one a caller will find. Note also what this constructor deliberately does not do: no printing, no file reading, no thread starting. A constructor whose failure mode is "the network was down" is far harder to reason about than one whose failure mode is "you asked for forty nights", and it makes the class awkward to use in a test.
The honest limits, and the design flaw is LEDGER. A constructor that writes to static state makes new Reservation(...) a non-local act: you cannot create one in a test without appending to a process-wide list, the list grows for the lifetime of the JVM with nothing to prune it, two threads constructing bookings will corrupt an unsynchronised ArrayList with no error at all, and the constructor has published information about a not-yet-finished object into shared state -- one careless edit from LEDGER.add(code) to LEDGER.add(this) and another thread can reach a half-built Reservation. Registration belongs to whoever wants a register, as an explicit call on an object that owns the list. Beyond that: extras is never null-checked, so passing null fails with an NullPointerException thrown from inside ArrayList's own constructor, naming nothing useful; ratePence is not validated at all, so a negative rate produces a negative total that every type in the program is happy with; the four consecutive int parameters mean new Reservation("R-9", 2, 11000, 2, caller) compiles and books two nights for eleven thousand guests at two pence; and totalPence() prices every extra at 500 pence whatever it is, which is a business rule hard-coded into the middle of an arithmetic method where nobody will look for it.
Common Mistakes
- Giving the constructor a return type.
public void Lift(String shaft)is a method namedLift, not a constructor. It compiles, it never runs onnew, and every field silently keeps its zero value.
- Expecting the no-arg constructor to survive. The compiler supplies one only when you declare none. Write any constructor and
new Thing()stops compiling -- which is usually correct, and occasionally a surprise in code you did not touch.
- A subclass that does not call
super(...)when it must. With no explicit call the compiler insertssuper(), and if the parent has no no-arg constructor the error names the parent class rather than the line you need to fix.
- Calling an overridable method from a constructor. The override runs against a subclass whose own constructor has not finished, so it reads
nulland0out offinalfields. Make such helpersprivate,staticorfinal.
- Doing real work in a constructor. Opening files, making network calls, starting threads or registering in a global list means
newcan fail for reasons that have nothing to do with the arguments, and it makes the class hard to construct in a test.
- Assigning a mutable argument straight to a field.
this.extras = extrashands the caller a permanent handle on your internal state. Copy it, and copy or wrap it again on the way out.
- Leaving a field unset in one of several constructors. Two constructors that each assign a different subset of fields will produce two subtly different kinds of object. Have one constructor assign everything and make the others delegate.
- Putting
this(...)orsuper(...)anywhere but first. It must be the first statement, full stop. The usual workaround -- a sharedinit()called from every constructor -- reintroduces mistake 4 unless that method isprivate.
- Assuming a constructor that throws left nothing behind. If it had already registered the object, opened a stream or started a thread, that side effect outlives the failed
new-- and you have no reference with which to clean it up.
Best Practices
- Validate every argument before assigning anything. A throw from the top of a constructor leaves no object at all; a throw from halfway down a constructor that has already touched static state leaves debris.
- Make fields
finaland assign every one of them in the constructor. The compiler then proves that noReservationexists with an unsetcode, which is a much stronger statement than any test can make.
- One constructor does the work; the others delegate with
this(...). Duplicated validation between two constructors stays in agreement exactly until someone edits one of them.
- Copy mutable arguments in and copy or wrap them out.
new ArrayList<>(arg)at the top andList.copyOf(field)in the getter are two lines that close the class properly.
- Keep constructors free of side effects. No printing, no I/O, no threads, no registering. If creating the object genuinely requires work, that work belongs in a named static factory the caller chooses to invoke.
- Never call an overridable method from a constructor, and prefer to make the class or the method
finalso nobody can introduce the problem later.
- Throw
IllegalArgumentExceptionwith the parameter name and the offending value."nights out of range: 40"costs one string concatenation and saves the next person a debugging session.
- Reach for a static factory or a builder once the parameter list grows. Constructors distinguished only by how many arguments they take stop being readable at about three, and a factory can have a name that says what it makes.
Practice Exercises
- The Vanishing Default. Add
Reservation r = new Reservation();tomainand record the exact compiler error. Then add a no-arg constructor back and work out what each of the fivefinalfields should be when the caller has supplied nothing -- write down your choice for each and what it would mean to the hotel. Finally, argue in two or three sentences for keeping or deleting that constructor, and say which of the three invariants it puts at risk.
- The Half-Built Report. Reproduce the
Trapoutput exactly, then fix it three separate ways: makerenderprivateinReportand see what breaks; move therender()call out of the constructor into astatic Boxed create(int, String)factory that builds the object and then calls it; and markReportfinalso no subclass can exist. Print the output of each version and state which one you would ship and why.
- The Ledger That Should Not Be There. Remove
LEDGERandledgerSize()fromReservationentirely. Write aRegisterclass holding a privateList<String>withvoid add(Reservation r)andint size(), create two registers, add different bookings to each, and print both sizes to prove they are independent. Then name one test that was impossible to write while the ledger lived in the constructor and is possible now, and write it.