Java Constructors: Chaining, Object Setup, and Publication
Understand Java constructor initialization, this() delegation cycles, JVM allocation choices, and safe publication with final fields.
Understand Java constructor initialization, this() delegation cycles, JVM allocation choices, and safe publication with final fields.
Java Constructors: Chaining, Object Setup, and Publication
Constructors establish an object’s invariants as part of Java’s class-instance creation process.
Introduction
The JLS specifies the observable steps of class-instance creation: any required class initialization occurs first, instance fields receive default values, and instance initialization and constructor bodies run before the reference is returned. It does not prescribe a concrete object layout or require each source-level new to leave a distinct allocation in optimized machine code. In HotSpot, escape analysis can let the JIT eliminate some non-escaping allocations through scalar replacement. That optimization is not a general stack-allocation guarantee. See the Java SE 27 JLS §12.5 and HotSpot escape analysis documentation.
Constructor bodies may have a restricted prologue before an explicit this(...) or super(...) invocation. The invocation separates that prologue from the rest of the body, and Java restricts references to the object under construction in the early construction context. Simple examples often place the invocation first. If a non-Object constructor has no explicit invocation, Java inserts super(); compilation fails when the parent has no accessible no-argument constructor. A this(...) chain that directly or indirectly invokes itself is a compile-time error, while recursion through ordinary methods or new expressions is evaluated at runtime. The Java SE 27 JLS §8.8.7 describes constructor bodies and their prologues.
One constructor hazard is the this escape: exposing this to another object before construction finishes. A listener can then call back while fields still have default values or before invariants are established. This article covers constructor overloads, chaining, copying, validation, and publication after construction.
When to use
Use constructors when:
- Mandatory fields must be set at creation time — use a constructor that requires them
- Validating object creation — reject invalid states before the object exists
- Setting up dependencies — inject collaborators that the object needs
- Providing convenience — multiple constructors for different initialization paths
public class Player {
private final String username;
private int health;
private int score;
// Primary constructor — requires username
public Player(String username) {
this.username = username;
this.health = 100;
this.score = 0;
}
// Convenience constructor — delegates to primary with defaults
public Player(String username, int health) {
this(username); // Delegation via this()
this.health = health;
}
}
When not to use
Avoid constructors for:
- Complex object creation — use the Builder pattern instead
- Creating objects with many optional parameters — too many constructor overloads
- Creating immutable objects with many fields — Builder or factory methods
- When factory methods better express intent —
Card.of(rank, suit)vsnew Card(rank, suit)
// Too many parameters — error-prone for callers
public Config(String host, int port, String user, String pass, boolean ssl, int timeout, boolean retries);
// Better: Builder pattern
public class ConfigBuilder {
public ConfigBuilder host(String host) { ... return this; }
public ConfigBuilder port(int port) { ... return this; }
public Config build() { return new Config(this); }
}
Constructor overloading diagram
classDiagram
class Player {
+Player(String username)$
+Player(String username, int health)$
+Player(String username, int health, int score)$
+Player(Player other)$
}
note for Player "Constructor Chaining\nthis() -> this(username) -> this(username, health)"
Failure scenarios
1. Forgetting to call this() or super()
If a class declares no constructors, Java supplies a default constructor whose body implicitly invokes super(). That child constructor still exists when the parent declares only parameterized constructors, but it fails to compile because the implicit call has no accessible no-argument target. An explicit child constructor must call a matching parent constructor.
The fix is to call super(name) explicitly when the parent requires parameters. If the parent has multiple constructors, pick the one that matches the state your subclass needs to inherit. The example below shows a Base class with a single parameterized constructor and a Derived class that fails to compile without an explicit super(name) call.
public class Base {
public Base(String name) { }
}
public class Derived extends Base {
public Derived() {
// super(); // IMPLICIT — but only if Base has no-arg constructor
// If Base only has parameterized constructor, this fails
}
}
// Fix: explicitly call super(name)
public class Derived extends Base {
public Derived(String name) {
super(name); // Explicit call required
}
}
2. Constructor delegation cycles and runtime recursion
The compile-time cycle rule applies to alternate constructor invocations: a constructor cannot directly or indirectly reach itself through a chain of this(...) calls. The Java SE 27 JLS §8.8.7.1 states this rule. A call to an ordinary method or a new expression inside a constructor is different; those are normal runtime calls and can recurse until runtime resources are exhausted.
class ConstructorCycle {
ConstructorCycle() {
this(1);
}
ConstructorCycle(int value) {
this(); // Compile-time error: this(...) chain cycles back
}
}
This separate example compiles, but constructing RuntimeRecursion recurses at runtime:
class RuntimeRecursion {
RuntimeRecursion() {
createAgain();
}
private void createAgain() {
new RuntimeRecursion();
}
}
Keep one terminal constructor for initialization and have the other constructors delegate toward it. For ordinary methods and object creation, provide a base case or stop condition as you would for any recursive call.
3. Letting this escape during construction
A this escape occurs when a constructor exposes its object before construction finishes. A callback may run immediately and observe fields before their assignments or invariants are complete. Even if the callback runs later, publishing this from the constructor makes the object’s initialization harder to reason about.
Here the listener runs during registration, before state is assigned, so it prints initialized null:
public class ThisEscape {
@FunctionalInterface
interface Listener {
void onEvent();
}
interface EventSource {
void registerListener(Listener listener);
}
static final class ImmediateSource implements EventSource {
public void registerListener(Listener listener) {
listener.onEvent();
}
}
private final String name;
private String state;
ThisEscape(EventSource source) {
name = "initialized";
source.registerListener(() -> System.out.println(name + " " + state));
state = "ready";
}
public static void main(String[] args) {
new ThisEscape(new ImmediateSource());
}
}
Safe publication
Completing a constructor and making its reference visible to another thread are separate steps. One simple publication mechanism is a volatile reference: the writer’s volatile assignment happens-before a reader that observes it. final fields also have initialization guarantees when the constructor completes without letting this escape, but final does not publish later changes to mutable fields. See Java SE 27 JLS §17.5.
public class SafePublication {
private static volatile Settings published;
static final class Settings {
private final int port;
Settings(int port) {
this.port = port;
}
int port() {
return port;
}
}
public static void main(String[] args) throws InterruptedException {
Thread reader = new Thread(() -> {
Settings settings;
while ((settings = published) == null) {
Thread.yield();
}
System.out.println(settings.port());
});
reader.start();
published = new Settings(8080); // volatile write safely publishes Settings
reader.join();
}
}
Save this as SafePublication.java, then run javac SafePublication.java && java SafePublication. It prints 8080 after the reader observes the published reference.
Trade-off table
| Constructor Type | Use Case | Limitation |
|---|---|---|
| Default (no-arg) | Simple classes, frameworks requiring empty constructor | Cannot enforce required fields |
| Parameterized | Mandatory fields must be set | Can get unwieldy with many parameters |
| Private | Singleton or factory controls direct creation | Only code with access can call it |
| Copy constructor | Create new instance from existing | Shallow copy unless explicitly deep |
Chained (this(...)) |
Share initialization between overloads | Must follow constructor-body prologue rules |
Code snippets
Constructor chaining with this()
Constructor overloads can delegate to one constructor so the field assignments stay in one place. Each shorter overload supplies defaults, then calls the fuller constructor with this(...).
The constructor body may contain a prologue, one explicit constructor invocation, and an epilogue. Java SE 27 permits a restricted prologue before this(...); the early construction context limits references to the object being created. In simple examples, the invocation is often the first line. When this(url, headers, body) runs, control transfers to the matching constructor. After that call returns, the delegating constructor’s epilogue runs.
In this HttpRequest example, the four-argument constructor assigns every field. Each shorter overload supplies a default for the missing arguments. A caller with only a URL gets a 30-second timeout, empty headers, and no body.
public class HttpRequest {
private final String url;
private final int timeout;
private final Map<String, String> headers;
private final String body;
// Base constructor — does real work
public HttpRequest(String url, int timeout, Map<String, String> headers, String body) {
this.url = url;
this.timeout = timeout;
this.headers = headers;
this.body = body;
}
// Chain to base with default timeout
public HttpRequest(String url, Map<String, String> headers, String body) {
this(url, 30000, headers, body);
}
// Chain with default headers
public HttpRequest(String url, String body) {
this(url, 30000, Map.of(), body);
}
// Chain with minimum required
public HttpRequest(String url) {
this(url, 30000, Map.of(), null);
}
}
Copy constructor
A copy constructor takes an existing instance of the same class and creates another instance from its state. The call new Player(existingPlayer) makes the copy operation explicit. Copy constructors are useful when a method should receive a separate instance instead of the caller’s object.
Decide whether the copy should be shallow or deep. Strings and primitive values can be reused safely. For a mutable field such as a list, storing the caller’s reference lets outside code change the list held by the new object. Creating a new list separates the list structure, though its elements are still shared unless they are copied too.
The Player constructor makes a new inventory list, and the copy constructor reuses that constructor. Adding or removing entries in the original list will not change the copy’s list. Since the example stores String values, sharing those immutable elements is safe; this is still a shallow copy of the object graph.
public class Player {
private final String name;
private int health;
private final List<String> inventory;
public Player(String name, int health, List<String> inventory) {
this.name = name;
this.health = health;
this.inventory = new ArrayList<>(inventory); // Defensive copy
}
// Copy constructor
public Player(Player other) {
this(other.name, other.health, other.inventory);
}
}
Observability checklist
- Required fields enforced via constructor parameters
- All constructor parameters validated before assignment
- Reference types defensively copied in constructor
- Explicit
this(...)orsuper(...)invocation follows constructor-body rules - No object escapes
thisbefore fully initialized
Security notes
- Validate inputs — reject invalid values before assignment
- Defensive copies — copy mutable objects passed as parameters
- Immutable fields — use
finaland assign in constructor only - Don’t publish
thisduring construction — callbacks may observe fields before initialization completes
public class SecureRequest {
private final List<String> allowedOrigins;
public SecureRequest(List<String> allowedOrigins) {
// Defensive copy — external list cannot affect our internal state
this.allowedOrigins = List.copyOf(allowedOrigins);
}
public List<String> getAllowedOrigins() {
return allowedOrigins; // Already immutable, safe to return
}
}
Pitfalls
- Forgetting
super()call — when parent has no default constructor, must explicitly call - Violating the “constructor should do minimal work” rule — heavy initialization in constructors hurts performance
- Creating objects in inconsistent state — don’t let object exist before invariants are established
- Too many constructor overloads — use Builder when parameter combinations become confusing
- Not defensive copying mutable parameters — storing direct references to mutable objects
// Bad: storing reference to mutable object
public class Cache {
private List<String> entries;
public Cache(List<String> entries) {
this.entries = entries; // External list can modify our data!
}
}
// Good: defensive copy
public class Cache {
private final List<String> entries;
public Cache(List<String> entries) {
this.entries = List.copyOf(entries); // Safe — we own our data
}
}
Quick recap
- Default constructor = supplied only when the class declares no constructors; fields receive default values during object creation
- Parameterized constructor = requires specific values at creation
- Constructor overloading = multiple constructors with different signatures
this(args)= delegate to another constructor in the same classsuper(args)= invoke a constructor in the direct superclass; Java suppliessuper()when omitted and accessible- Copy constructor =
new Player(existingPlayer)pattern for cloning
Interview questions
Further reading
- Java SE 27 JLS §8.8.7 — constructor body structure and prologue rules
- Java SE 27 JLS §8.8.7.1 — constructor invocation and
this(...)cycles - Java SE 27 JLS §17.5 — final-field initialization semantics
- Java SE 27 HotSpot escape analysis — allocation elimination and scalar replacement
- Fields and Instance Variables — understanding state initialization
- Classes and Objects — the new keyword and instantiation
- Inheritance in Java — super() and parent initialization
Conclusion
Constructors establish an object’s state as part of Java’s specified object-creation process. Validate required values and complete initialization before making the reference available to other code.
The distinction between default and parameterized constructors matters for API design: default constructors suit simple classes where all fields have sensible defaults, while parameterized constructors enforce that critical data is supplied at creation. Constructor overloading provides multiple initialization paths, with this() chaining reducing duplication by directing all paths to a single constructor that does the actual work.
Constructor bodies may have a restricted prologue before this(...) or super(...); the Java SE 27 JLS limits references to the object under construction in that context. If a non-Object constructor has no explicit invocation, Java inserts super() when an accessible no-argument parent constructor exists. A this(...) delegation cycle is rejected at compile time, while recursion through methods or new calls happens at runtime.
Validate inputs, copy mutable parameters when the class needs its own collection structure, and use final fields for values that should not change after construction. These choices make invalid state harder to create and reduce accidental mutation.
If a constructor throws, the new expression does not return a reference. A constructor that exposes this before that point can still leak the instance, so keep construction separate from listener registration and publication. For field order, see Fields and Instance Variables; for object creation, see Classes and Objects.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.