Java Constructors: Chaining, Object Setup, and Publication

Understand Java constructor initialization, this() delegation cycles, JVM allocation choices, and safe publication with final fields.

published: reading time: 17 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

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) vs new 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(...) or super(...) invocation follows constructor-body rules
  • No object escapes this before fully initialized

Security notes

  • Validate inputs — reject invalid values before assignment
  • Defensive copies — copy mutable objects passed as parameters
  • Immutable fields — use final and assign in constructor only
  • Don’t publish this during 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

  1. Forgetting super() call — when parent has no default constructor, must explicitly call
  2. Violating the “constructor should do minimal work” rule — heavy initialization in constructors hurts performance
  3. Creating objects in inconsistent state — don’t let object exist before invariants are established
  4. Too many constructor overloads — use Builder when parameter combinations become confusing
  5. 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 class
  • super(args) = invoke a constructor in the direct superclass; Java supplies super() when omitted and accessible
  • Copy constructor = new Player(existingPlayer) pattern for cloning

Interview questions

1. What happens if you don't define any constructor in a class?
If a class declares no constructors, Java provides a default no-argument constructor. Instance fields receive default values during object creation before field initializers and constructor bodies run. Declaring any constructor suppresses the default constructor.
2. What is constructor chaining?
Constructor chaining is when one constructor invokes another constructor in the same class with `this(args)`. One constructor can perform the initialization while the others supply defaults. Java SE 27 allows a restricted prologue before the explicit invocation; see JLS §8.8.7.
3. Can a constructor call a method?
Yes. Avoid calling overridable methods before construction finishes because a subclass override can observe fields that still have default values. A `final` helper avoids overriding, but it should still use only state that has already been initialized.
4. What is the difference between `this()` and `super()` in constructors?
`this(...)` invokes another constructor in the same class; `super(...)` invokes a constructor in the direct superclass. A constructor body can have a restricted prologue before its explicit invocation, but it can contain only one such invocation, so it cannot use both.
5. Why should mutable object parameters be copied in constructors?
Storing the caller's mutable object directly lets later changes affect the constructed object's state. Copy the collection or use an unmodifiable copy when the class needs to keep its own structure.
6. What happens when a constructor throws an exception during object creation?
The `new` expression completes abruptly with the exception, so an assignment such as `value = new Thing()` does not update `value`. The object may still be observable if its constructor leaked `this` before throwing; otherwise it becomes eligible for garbage collection once no references remain.
7. Can constructors be called recursively by using this()?
A cycle formed by direct or indirect `this(...)` constructor invocations is a compile-time error (JLS §8.8.7.1). Recursion through an ordinary method call or a `new` expression is runtime recursion instead.
8. What is a copy constructor and when would you use one?
A copy constructor takes an instance of the same class and creates another instance from its state. Decide whether to copy mutable fields deeply or shallowly; copying references alone does not make the objects independent.
9. What can appear before an explicit `this(...)` or `super(...)` invocation?
Java SE 27 constructor bodies may contain a restricted prologue before the invocation. The early construction context prevents using the object under construction before its superclass or alternate constructor has run. See JLS §8.8.7.
10. Can you have a constructor that returns a value?
Constructors have no declared return type. A bare `return;` can exit a constructor early, but it does not return a value; the `new` expression yields the reference after construction completes.
11. What is the difference between default and parameterized constructors?
If a class declares no constructor, Java provides a default no-argument constructor. A parameterized constructor accepts arguments. Declaring any constructor suppresses the default constructor.
12. What happens if you call this() and super() in the same constructor?
A constructor body contains at most one explicit constructor invocation. Choose either `this(...)` to delegate within the class or `super(...)` to invoke the direct superclass constructor.
13. What is the constructor execution order in a class hierarchy?
In Java SE 27, a restricted subclass prologue can run before the explicit `super(...)` invocation. The superclass constructor chain runs next; after it returns, the subclass's instance initializers and constructor epilogue run. Static initialization happens separately when the class is initialized.
14. What is a private constructor and what pattern uses it?
A private constructor prevents code outside the class from calling it directly. A class may use one to control creation through a factory or to implement a singleton.
15. How does the Builder pattern improve constructor usability?
A builder moves optional choices out of a long constructor parameter list. Its methods configure the builder, and `build()` validates the collected values and creates the object.
16. What happens to instance fields if a constructor fails mid-execution?
There is no automatic rollback. Fields assigned before the exception keep those values in the abandoned instance; fields not yet assigned retain their default values. The `new` expression throws and does not return the reference, though a constructor that leaked `this` can expose the instance.
17. Can an abstract class have a constructor and why?
Yes. An abstract class constructor initializes its part of a subclass instance. The constructor chain invokes it through `super(...)`, explicitly or through an inserted `super()` when available.
18. What is constructor overloading and how does it relate to this() chaining?
Constructor overloading means a class declares constructors with different parameter lists. One constructor can invoke another with `this(args)` to share initialization code.
19. How do you prevent the `this` reference from escaping during construction?
Do not register callbacks or store `this` in another object before construction completes. Finish initialization first, then register listeners or publish the reference through a safe mechanism such as a `volatile` field or synchronized access.
20. What is the relationship between field initialization and constructor execution order?
The constructor's restricted prologue runs before an explicit `super(...)`. After the superclass constructor returns, the class's instance field initializers and initializer blocks run in textual order, followed by the constructor epilogue. Class initialization is separate.

Further reading

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.

#java-abstract-classes #java #java-fundamentals

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-arithmetic-operators #java #java-fundamentals

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.

#java-array-basics #java #java-fundamentals