Skip to content
javahacks.dev
Java Core

Java Constructors and Initialization Order Explained

How Java constructors work: chaining with this and super, default constructors, the danger of calling overridable methods, final fields and records.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the OpenJDK, JUnit5, Spring and Gradle logos.

A constructor looks like the simplest thing in Java: a method with the class's name that sets up an object. Then a subclass overrides a method that the parent's constructor calls, and the override sees null in a field that was assigned two lines above in the source. Or a static field is initialized after the code that reads it. Or a class works the first time and throws a different error on the second use. All of these come from the same fact: construction is a fixed sequence of steps, in an order that source code layout does not reveal. This post runs one class hierarchy and prints the order, explains each step, shows the overridable-method trap with real output, covers final fields and immutability, alternatives to piles of constructors, records, constructors that throw and the cases of enums and anonymous classes. The output below was produced by running the code on JDK 17; the order is defined by the Java Language Specification and is the same in every version.

The basics

A constructor has the name of its class, no return type, and runs when you write new. If you declare none, the compiler supplies a no-argument one. If you declare any, the default disappears. A constructor can call another constructor of the same class with this(...) or the parent's with super(...), and such a call must be the first statement:

java
public class Customer {

    private final String name;
    private final String email;

    public Customer(String name) {
        this(name, name.toLowerCase().replace(' ', '.') + "@example.test");
    }

    public Customer(String name, String email) {
        this.name = name;
        this.email = email;
    }
}

this(...) chains constructors so that the real initialization lives in one place. If the first statement is neither, the compiler inserts super(), the parent's no-argument constructor. That implicit call is the source of "constructor not found" errors in subclasses of a class that has only parameterized constructors. The details are in section 8.8 of the language specification, and the tutorial introduction is Oracle's constructors lesson.

The order of events

When you create an object of a subclass, things happen in this sequence: the class is initialized if it is not yet (parent first, then child), then memory is allocated with default values, then the constructor chain runs from the parent down, and within each class the field initializers and instance blocks run before the constructor body. Print it:

src/main/java/dev/javahacks/init/Init.javajava
public class Init {

    static class Base {
        static { System.out.println("1 Base static block"); }
        protected String name = init("Base field");
        { System.out.println("3 Base instance block"); }

        Base() {
            System.out.println("4 Base constructor");
            describe();
        }

        void describe() { System.out.println("Base.describe"); }

        static String init(String s) {
            System.out.println("2 " + s + " initializer");
            return s;
        }
    }

    static class Child extends Base {
        static { System.out.println("1b Child static block"); }
        private String label = "set";
        { System.out.println("6 Child instance block, label=" + label); }

        Child() {
            super();
            System.out.println("7 Child constructor");
        }

        @Override
        void describe() { System.out.println("5 Child.describe sees label=" + label); }
    }

    public static void main(String[] args) {
        System.out.println("main starts");
        new Child();
    }
}
Text
main starts
1 Base static block
1b Child static block
2 Base field initializer
3 Base instance block
4 Base constructor
5 Child.describe sees label=null
6 Child instance block, label=set
7 Child constructor

Read the numbers as the order. Static blocks run once, when the class is first used, parent before child. Then for the parent: field initializers and instance blocks in textual order (2, 3), then the constructor body (4). Only then does the child's turn come: its initializers (6) and its constructor body (7). The same story is told for static initialization in more detail in static initialization order versus instance order.

The overridable method trap

Line 5 is the trap. The parent's constructor (4) called describe(), which is overridden in the child. Java dispatches to the child's version, since the object is already a Child, but the child's fields are not initialized yet: label is null, because its initializer is step 6, which comes after the parent's constructor finishes. The child method ran on a half-built object.

This is a real source of bugs: a base class constructor that calls an overridable init() or setup() hook, and subclasses whose override reads their own fields. The rules that keep you out of it:

  • Never call an overridable method from a constructor. Call only private, final or static methods, or make the class final.
  • **Do not publish this from a constructor.** Registering the object as a listener or starting a thread inside the constructor lets another thread see it before the fields are assigned; the memory-visibility reasoning is in the Java memory model and happens-before.
  • **Prefer a factory or an explicit start().** Construct, then initialize in a separate call that the creator makes.

Frameworks have their own timing for initialization callbacks, such as @PostConstruct, which run after construction and injection; the Spring view of the same problem is in constructor injection versus field injection.

Final fields and immutability

A final field must be assigned exactly once, by the end of every constructor. The compiler checks it, which is why final fields make a class easier to reason about. Beyond the check, the Java memory model gives final a special guarantee: after the constructor completes, any thread that sees the object also sees the correct values of its final fields, without synchronization (provided this did not escape during construction). That is why immutable classes built from final fields are safe to share between threads.

java
public final class Money {

    private final long cents;
    private final String currency;

    public Money(long cents, String currency) {
        if (currency == null || currency.length() != 3) {
            throw new IllegalArgumentException("currency must be a 3-letter code");
        }
        this.cents = cents;
        this.currency = currency;
    }
}

Validate in the constructor, before the object can be used, so no instance of the class can be in an invalid state. Defensive-copy mutable arguments (List.copyOf(items)) so the caller cannot change them later.

Alternatives to many constructors

A class with five optional fields grows a constructor for every combination. Three alternatives are better. A static factory has a name: Money.ofCents(500, "USD") is clearer than new Money(500, "USD") and can return a cached or subclass instance. A builder lets the caller set only what they need and validates in build(), and with records the pattern gets shorter, as shown in the builder pattern with records. Defaults through chaining (this(...)) works when there are two or three variants. Pick by how many parameters there are: up to three, constructors; four or more with optional ones, a builder.

Records

A record declares its components in the header, and the compiler generates the canonical constructor, accessors, equals, hashCode and toString. Add validation in a compact constructor, which runs before the fields are assigned:

java
public record Quantity(int value) {

    public Quantity {
        if (value < 0) {
            throw new IllegalArgumentException("x must be >= 0");
        }
    }
}
Text
x must be >= 0

The compact form has no parameter list and no assignments: the parameters are in scope, you may reassign them to normalize the value (name = name.strip()), and the fields are assigned automatically at the end. Records are implicitly final with final fields, so the issues above (overridable calls, half-built state) cannot arise for them.

Constructors that throw

If a constructor throws, no object is returned and the allocated memory is reclaimed, but anything the constructor already did stays done: a file it opened, a thread it started, a registration in a static map. The finalize hazard is gone from modern Java (it is deprecated for removal), so do not rely on cleanup of a partially built object; acquire resources last, or in a factory method that wraps construction in try/finally.

A related case is static initialization failing. The first attempt throws ExceptionInInitializerError; the class is then marked unusable, and every later use throws a different error:

java
static class Broken {
    static final int N = Integer.parseInt("not a number");
}
Text
java.lang.ExceptionInInitializerError: null
java.lang.NoClassDefFoundError: Could not initialize class Init$Broken

The first message is the cause; the second, on every following access, is the symptom that appears in logs long after. If you see Could not initialize class, search backward for the first ExceptionInInitializerError and read its cause, as covered in ClassNotFoundException and NoClassDefFoundError.

Enums, anonymous classes

Enum constructors are private and run once per constant, at class initialization, in declaration order; an enum constructor cannot refer to a static field of the enum (other than constants), because statics are not initialized yet at that point. Anonymous classes have no name and so no constructor of their own: arguments go to the parent's constructor, and an instance initializer block ({ ... }) is the only place for setup code.

java
List<String> names = new ArrayList<>() {{ add("Ada"); add("Grace"); }};   // double-brace: avoid

The double-brace idiom creates an anonymous subclass of ArrayList that holds a reference to the enclosing instance, which is a hidden leak and breaks equals symmetry. Use List.of(...) instead.

Where this does not apply

If your objects are created by a framework through a no-argument constructor and populated by setters or field injection (JPA entities, some serialization libraries), the order described above still holds for the constructor, but the state you care about arrives afterward, and a constructor that validates will reject the instance the framework builds first. JPA needs a protected no-argument constructor for that reason. For classes with no fields and no invariants, the default constructor is all you need.

Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.