Lesson · Classes and Objects
Constructors: the rules, and the patterns on top
16 min readConstructors
A constructor gives an object its first legal state. The compiler writes one until you write your own, chaining runs before any body touches state, and this(...) keeps several constructors in agreement.
The contract
A constructor gives an object its first legal state. It runs after fields receive their defaults and after instance initialiser blocks, and the object is only handed to the caller once the constructor finishes. There is no way to re-run a constructor on an existing object, which is the whole point: construction happens exactly once, and everything afterwards must respect the invariants it established.
The rules fit in one table, and each row explains a familiar error message:
| Rule | Detail |
|---|---|
| Name | Must match the class name exactly |
| Return type | None, not even void |
| Inheritance | Never inherited, never overridden |
| Overloading | Freely: several parameter lists, funneling into one canonical constructor |
| Runs when | After field defaults and initialiser blocks, before the caller sees the reference |
| Throws | No object escapes: the reference is never handed out |
Construction is the one moment a half-built object is allowed to exist. A constructor that throws means nothing escaped, which is why validation belongs here and nowhere else.
The compiler's freebie, and this(...)
If a class declares no constructor at all, the compiler inserts a public no-argument one. The moment you declare any constructor, the freebie disappears: a class with only Money(long cents, String currency) has no no-arg constructor, and anything that previously compiled against one stops. This is usually a feature, since half-initialised objects are not a state worth supporting.
this(...) calls another constructor of the same class, and it must be the first statement of the calling constructor. The chain runs innermost first, so the most specific constructor owns the field assignments. Cycles are impossible by construction: the compiler rejects a chain that comes back to itself.
The chain, traced for new Money(125) when Money(long) forwards to Money(long, String):
Money(125)starts and immediately callsthis(125, "USD"), so the two-argument constructor runs first.- The two-argument constructor validates both values and assigns both fields.
- Control returns to the one-argument body, which by then has nothing left to do.
The most specific constructor owns the assignments. Every other constructor funnels into it, so there is one place to audit and one place where defaults are decided.
Constructor lab
pick a constructWith no declared constructors, the compiler inserts a public no-argument one. The moment you declare any constructor, this freebie disappears.
The compiler only ever writes one constructor for you, and only when you write none.
super() and the invisible first call
Every constructor begins with a call to either this(...) or super(...), and if you write neither, the compiler inserts super() with no arguments. That invisible line is why the parent's construction completes before the child's fields initialise, and why a child whose parent lacks a no-arg constructor must call super(args) itself.
The order for new Dog("Rex"), where Dog extends Animal:
- The Dog constructor begins with an implicit
super(), or your explicitsuper(args)when the parent has no no-arg constructor. - The Animal constructor runs to completion first: its defaults, its initialisers, its body.
- Only then do Dog's field initialisers and constructor body run, and finally the reference is handed back.
One straight line from Object down to your class. Every constructor on the path runs, top first, and nothing of the child executes before the parent finishes. The initialization-order topic follows this thread to its full conclusion.
Patterns: factories, privacy, builders
Three patterns sit on top of the mechanics, and they are chosen, not memorised:
| Pattern | Shape | Buys | Trade-off |
|---|---|---|---|
| Static factory | Money.ofDollars(2) | A name, caching, subtype returns | Not obvious as a constructor; blocks subclassing |
| Private constructor | private Util() {} | Seals the class: no instantiation | Also blocks subclassing, deliberately |
| Builder | Money.builder().build() | Ends the telescoping problem for many fields | More code; overkill below three or four fields |
Validate in the constructor. Objects.requireNonNull for references, a range check for numbers, an IllegalArgumentException with a useful message. An object that exists is an object that is valid, and every later method gets to assume so.
Choosing the shape
Which pattern to reach for, as a short sequence:
- One field whose interpretation changes the others? Validate in the constructor before assigning anything.
- Several optional fields? Above three or four, a builder; below that, overloads that funnel into one canonical constructor.
- A creation path that deserves a name? A static factory (
of,valueOf,from,parse), as the JDK does throughout. - A class that should never be instantiated? A private constructor; for singletons, an enum is the modern answer.
- An argument that may be null?
Objects.requireNonNull(value, "value")at construction, with the name in the message.
One canonical constructor, every path funnels into it, every invalid argument rejected before a field is set. That shape audits itself.
this(...) must be the first statement
Not the first line, the first statement, and the compiler enforces it because the chained constructor must complete before your body touches any state. Work you wanted to do before chaining (computing a default, normalising an argument) goes into the arguments of the this(...) call itself or into a static helper.
Interview angles
When does the compiler provide a constructor?+
Only when the class declares none. One declared constructor, even a private one, removes the free no-arg version entirely. That is often deliberate (forcing callers through a factory) and occasionally a breaking change nobody saw coming.
Can a constructor return a value, be inherited, or be overridden?+
No to all three. It has no return type, is not inherited, and cannot be overridden; it can be overloaded. Its only job is establishing the initial state of a brand-new object at the one moment that is possible.
What do static factories buy over new?+
Names (of, valueOf, from, parse), caching (Boolean.valueOf), subtype selection, and freedom to change the return type later. The trade-offs are that they are not obvious as constructors and cannot be used by subclasses, which is why the JDK uses both.
Where should argument validation live?+
In the constructor, before any field is set, throwing IllegalArgumentException or NullPointerException with a precise message. An object that escapes the constructor is then guaranteed valid, which every method afterwards relies on.
What is the telescoping constructor problem?+
A class with several fields where each combination of optional values produces another overlapping constructor. Readers lose track of argument order and adding a field multiplies the set. A builder collects named values and calls one canonical constructor at build() instead.