- Prerequisites
- 4.1 Classes · 4.2 Objects
- Covers
- Default constructor · Parameterized constructor · Constructor overloading · Constructor chaining · this() · super()
- Related
- 6.1 Inheritance · Book 5 Vol III (Builder, Factory Method) · Book 4 (constructor injection)
On this page
1Concept / Definition
A constructor is a special member that initialises a new object. It has the same name as its class, no return type, and runs as part of new after memory is allocated and zeroed. Its job is to leave the object in a valid state, so that every method can rely on the class's invariants from the first call.
2Why It Exists
Without constructors, every object would start with its fields at their default values: null references, zero numbers and false flags. Callers would have to remember to call an initialisation method, in the right order, before using the object, and nothing would stop them from using one that was only half set up. A constructor ties creation and initialisation together: no object can be obtained without running one, so the checks in it hold for every instance, and every method can rely on them.
Constructors also make immutability possible. A final field must be assigned exactly once, by the end of construction, and the Java memory model guarantees that other threads see the values that the constructor gave to final fields, provided this did not escape before it finished. Records, value objects and constructor injection in frameworks such as Spring all build on these two guarantees.
3Core Concepts
Default constructor
If a class declares no constructors, the compiler adds a default constructor: no parameters, the same access as the class, and a body that only calls super(). As soon as any constructor is declared, the default is no longer generated, which is a frequent cause of "no suitable constructor" errors when a framework or subclass expects one.

Parameterized constructor
A constructor with parameters receives the values the object needs to be valid and checks them. It is the natural place for invariants: required fields are non-null, numbers are in range, collections are copied defensively.
Constructor overloading
A class can declare several constructors with different parameter lists, chosen by the same overload rules as methods (4.4). Overloading provides convenient forms — for example with and without a default currency. Too many overloads with similar parameter types become ambiguous to read; static factory methods with names (Money.ofMinor(...)) or a builder are clearer.
Constructor chaining
Every constructor begins by invoking another constructor: either one of its own class with this(...), or one of its superclass with super(...). If neither is written, the compiler inserts super(). The chain therefore always runs up to Object(), and the constructor bodies then complete from the top of the hierarchy down.

this()
this(...) delegates to another constructor of the same class. It keeps validation and assignment in one primary constructor that the others call, avoiding duplicated logic.
super()
super(...) calls a superclass constructor, so the inherited part of the object is initialised first. If the superclass has no no-argument constructor, every subclass constructor must call super(...) explicitly with suitable arguments.

4How It Works Internally
javac compiles each constructor to a method named <init> (4.1). Its body starts with the call to this(...) or super(...), written or implicit. In a constructor that calls super(...), javac then inserts the class's field initialisers and instance initialiser blocks, in text order, and only after them the rest of the body. A constructor that calls this(...) gets no copy, because the constructor it delegates to already runs them; that is why initialisers run exactly once per object however the constructors are chained (Figure 4). This small class shows both cases:
public class Point {
private final int x;
private final int y;
private String label = "point"; // field initialiser
public Point(int x, int y) { // calls super(): gets the initialiser
this.x = x;
this.y = y;
}
public Point() { // calls this(...): does not
this(0, 0);
}
static Point make() { return new Point(1, 2); }
}javap shows what javac generated (the constant-pool numbers after # vary between compilers, and the padding before the comments is shortened here):
$ javap -c -p Point
public Point(int, int);
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: aload_0
5: ldc #7 // String point
7: putfield #9 // Field label:Ljava/lang/String;
10: aload_0
11: iload_1
12: putfield #15 // Field x:I
15: aload_0
16: iload_2
17: putfield #19 // Field y:I
20: return
public Point();
Code:
0: aload_0
1: iconst_0
2: iconst_0
3: invokespecial #22 // Method "<init>":(II)V
6: return
static Point make();
Code:
0: new #10 // class Point
3: dup
4: iconst_1
5: iconst_2
6: invokespecial #22 // Method "<init>":(II)V
9: areturn
At the call site, new Point(1, 2) compiles to three steps: new allocates the object, with its fields zeroed and its header written; dup keeps a second copy of the reference; and invokespecial runs <init> on it. The caller can use the reference only after <init> returns. Until then the object exists but is incomplete, which is what the overridable-method trap in section 7 exposes: while Base's constructor runs, the object is already a Child, so a virtual call reaches Child's method before Child's initialisers have run.
For final fields the Java memory model adds one more step at the end of the constructor, often called the freeze: any thread that later obtains a reference to the object, even through a data race, sees the values the constructor gave to its final fields. Non-final fields get no such guarantee, and neither do final fields if this escaped before the constructor finished.
5APIs / Features / Syntax
The forms a constructor can take, and the language features related to them:
| Form | Example | Notes |
|---|---|---|
| Default (generated) | (no constructor declared) | No parameters, same access as the class; the body only calls super() |
| No-argument | protected Customer() {} | Required by JPA and some serialisers; protected keeps it out of normal use |
| Parameterised | Money(BigDecimal amount, Currency c) | Checks and assigns everything the object needs |
| Private | private Config() {} | Utility classes and singletons; forces callers through a factory or builder (Example 5) |
| Copy constructor | Basket(Basket other) | Safer than clone(): runs the normal checks and copies mutable parts (4.2) |
| Canonical (record) | record Point(int x, int y) | Generated: assigns every component |
| Compact canonical (record) | Point { if (x < 0) throw ...; } | Validates or normalises the parameters before they are assigned (Example 4) |
| Enum constructor | Status(String label) | Always private; runs once for each constant |
| Prologue (Java 25) | statements before super(...) | Validate or compute arguments; cannot use this (Example 3) |
Constructors are not inherited and cannot be static, final or abstract, and they declare no return type, not even void: a "constructor" with void in front of it is an ordinary method that happens to have the class's name. A class that declares only private constructors cannot be instantiated or subclassed from outside, which is how factories, builders and utility classes control creation.
6Practical Examples
Example 1 — A primary constructor, an overload and a factory
public class Money {
private final BigDecimal amount;
private final Currency currency;
public Money(BigDecimal amount, Currency currency) { // primary constructor
this.currency = Objects.requireNonNull(currency, "currency");
this.amount = Objects.requireNonNull(amount, "amount")
.setScale(currency.getDefaultFractionDigits(),
RoundingMode.HALF_EVEN);
}
public Money(String amount, String currencyCode) { // convenience overload
this(new BigDecimal(amount), Currency.getInstance(currencyCode));
}
public static Money zero(Currency currency) { // named factory
return new Money(BigDecimal.ZERO, currency);
}
}What to notice. All validation and scaling happen in the primary constructor; the String overload only converts its arguments and delegates with this(...), and the factory zero delegates too. However a Money is created, the same rules run, and a rule changed in one place applies to every path.
Example 2 — Mini program: watching a constructor chain run
Problem. Section 3 says that constructors chain up to Object and that the bodies then complete from the top down. This program logs every step for a two-level hierarchy whose convenience constructor delegates with this(...) to a primary constructor, which calls super(...).
public class ChainTrace {
static void log(String s) { System.out.println(s); }
static String init(String s) { log(" " + s); return s; }
static class Account {
private final String created = init("Account field initialiser");
protected final String id;
Account(String id) { // implicit super() -> Object()
this.id = id;
log(" Account(String) body, id = " + id);
}
}
static class SavingsAccount extends Account {
private final String audit = init("SavingsAccount field initialiser");
private final double rate;
SavingsAccount(String id) { // convenience constructor
this(id, 3.5);
log(" SavingsAccount(String) body");
}
SavingsAccount(String id, double rate) { // primary constructor
super(id);
if (rate < 0) throw new IllegalArgumentException("rate < 0");
this.rate = rate;
log(" SavingsAccount(String, double) body, rate = " + rate);
}
}
public static void main(String[] args) {
log("new SavingsAccount(\"SB-1\"):");
new SavingsAccount("SB-1");
log("new SavingsAccount(\"SB-2\", 4.0):");
new SavingsAccount("SB-2", 4.0);
}
}new SavingsAccount("SB-1"):
Account field initialiser
Account(String) body, id = SB-1
SavingsAccount field initialiser
SavingsAccount(String, double) body, rate = 3.5
SavingsAccount(String) body
new SavingsAccount("SB-2", 4.0):
Account field initialiser
Account(String) body, id = SB-2
SavingsAccount field initialiser
SavingsAccount(String, double) body, rate = 4.0Why it behaves this way. SavingsAccount(String) starts with this(id, 3.5), so nothing of its own runs until the primary constructor has finished. The primary constructor starts with super(id), so Account is initialised first: its field initialiser, then its body. Only then do SavingsAccount's field initialiser and the rest of the primary constructor run, and last the remainder of the convenience constructor. The second object, created through the primary constructor directly, shows the same sequence without the last line. SavingsAccount's field initialiser runs once in both cases, because javac copied it only into the constructor that calls super(...) (Figure 4).
Example 3 — Validating before super(...) in Java 25
public class CreditAccount extends Account {
public CreditAccount(String id, BigInteger limit) {
if (limit.signum() <= 0) { // Java 25 prologue
throw new IllegalArgumentException("limit must be positive");
}
super(id, limit); // then the super call
}
}What to notice. Before Java 25 the check could not come first, because super(...) had to be the first statement; code either validated after the superclass had already stored the value, or squeezed the check into a static helper, super(id, requirePositive(limit)). The prologue may read the parameters and call static methods, but not use this. Flexible constructor bodies were a preview feature in Java 22 to 24 and are final in Java 25.
Example 4 — Records: a compact constructor validates and normalises
Problem. A record's canonical constructor is generated, but most records still need rules: a date range whose end is before its start, or a list that the caller can change afterwards, should not be possible. A compact canonical constructor adds those rules without repeating the assignments.
public class DateRangeDemo {
record DateRange(LocalDate from, LocalDate to) {
DateRange { // compact canonical constructor
Objects.requireNonNull(from, "from");
Objects.requireNonNull(to, "to");
if (to.isBefore(from))
throw new IllegalArgumentException(from + " is after " + to);
}
static DateRange ofDays(LocalDate from, int days) { // named factory
return new DateRange(from, from.plusDays(days - 1));
}
long days() { return ChronoUnit.DAYS.between(from, to) + 1; }
}
record Tags(List<String> values) {
Tags { values = List.copyOf(values); } // unmodifiable copy
}
public static void main(String[] args) {
DateRange sale = DateRange.ofDays(LocalDate.of(2026, 3, 30), 5);
System.out.println(sale + ", days = " + sale.days());
try {
new DateRange(LocalDate.of(2026, 4, 10), LocalDate.of(2026, 4, 1));
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
List<String> source = new ArrayList<>(List.of("new"));
Tags tags = new Tags(source);
source.add("clearance"); // caller changes its list later
System.out.println(tags);
try {
tags.values().add("hacked");
} catch (UnsupportedOperationException e) {
System.out.println("rejected: values() is unmodifiable");
}
}
}DateRange[from=2026-03-30, to=2026-04-03], days = 5
rejected: 2026-04-10 is after 2026-04-01
Tags[values=[new]]
rejected: values() is unmodifiableWhy it behaves this way. A compact constructor has no parameter list; its body runs first, on the parameters, and the compiler assigns the fields after it. That is why Tags can replace values with List.copyOf(values): the field receives the copy, so the caller's later add("clearance") does not reach the record, and the copy is unmodifiable, so values().add fails too. DateRange.ofDays is a named factory that still goes through the canonical constructor, so the range check also applies to it. Every way of creating a record ends in the canonical constructor, deserialisation by Jackson included, which makes it the safest place for invariants.
Example 5 — Telescoping constructors versus a builder
Problem. A client configuration has one required value and three optional ones. With constructors that becomes a ladder of overloads, and a call such as new ClientConfig(url, 2000, 2, true) does not say which number is which. A builder names each value and keeps the one validating constructor.
public class BuilderDemo {
static final class ClientConfig {
private final String baseUrl;
private final int timeoutMs;
private final int retries;
private final boolean gzip;
private ClientConfig(Builder b) { // the one validating constructor
if (b.baseUrl == null)
throw new IllegalStateException("baseUrl is required");
if (b.timeoutMs <= 0)
throw new IllegalStateException("timeoutMs must be > 0");
this.baseUrl = b.baseUrl;
this.timeoutMs = b.timeoutMs;
this.retries = b.retries;
this.gzip = b.gzip;
}
static Builder builder() { return new Builder(); }
static final class Builder {
private String baseUrl;
private int timeoutMs = 2_000; // defaults live in one place
private int retries = 2;
private boolean gzip;
Builder baseUrl(String v) { baseUrl = v; return this; }
Builder timeoutMs(int v) { timeoutMs = v; return this; }
Builder retries(int v) { retries = v; return this; }
Builder gzip(boolean v) { gzip = v; return this; }
ClientConfig build() { return new ClientConfig(this); }
}
@Override public String toString() {
return baseUrl + " timeout=" + timeoutMs + "ms retries=" + retries
+ " gzip=" + gzip;
}
}
public static void main(String[] args) {
// telescoping: new ClientConfig("http://inventory-svc", 2000, 2, true)
System.out.println(ClientConfig.builder()
.baseUrl("http://inventory-svc").gzip(true).build());
System.out.println(ClientConfig.builder()
.baseUrl("http://pricing-svc").timeoutMs(500).retries(0)
.build());
try {
ClientConfig.builder().gzip(true).build();
} catch (IllegalStateException e) {
System.out.println("rejected: " + e.getMessage());
}
}
}http://inventory-svc timeout=2000ms retries=2 gzip=true
http://pricing-svc timeout=500ms retries=0 gzip=false
rejected: baseUrl is requiredWhy it behaves this way. The constructor of ClientConfig is private, so build() is the only way in, and it passes the builder to that constructor, where the required value and the ranges are checked once. Defaults are written once, in the builder's fields, and each call sets only what differs. The result is still an immutable object with final fields. The cost is a second class to maintain; for two or three parameters, a constructor or a record with a static factory is simpler.
7Common Problems & Mistakes
| Mistake | Why it is a problem | Fix |
|---|---|---|
| Calling an overridable method from a constructor | The subclass override runs before the subclass's fields are initialised | Call only private or final methods from constructors |
| Letting this escape (registering a listener, starting a thread) | Other threads see a partly constructed object | Register or start after construction, e.g. in a factory |
| Telescoping constructors with many parameters | Unreadable calls, easy to swap arguments | Builder or parameter object |
| Duplicated validation in several constructors | Rules drift apart | Chain to one primary constructor |
| Removing the implicit default constructor unintentionally | Frameworks or subclasses fail | Declare a no-arg constructor where required (e.g. JPA, protected) |
| Slow or failing work in a constructor (files, network) | Objects are slow to create and hard to test, and a failure half-way leaves resources such as open files behind | Pass the data in, or do the work in a factory or a start() method (Figure 5) |
| Storing a caller's mutable argument without a copy | The caller can change the object later, bypassing every check the constructor made | Copy defensively, e.g. List.copyOf in a compact constructor (Example 4) |
| Validating only after super(...) has used the argument | The superclass may store or act on an invalid value before the check runs | Validate in a Java 25 prologue, or in a static helper passed to super(...) |
class Base {
Base() { describe(); } // overridable call: dangerous
void describe() { }
}
class Child extends Base {
private String name = "child";
@Override void describe() {
// NullPointerException: name not yet set
System.out.println(name.length());
}
}Run as it stands, this code throws NullPointerException: while Base() runs, name still has its default value, null. One detail can hide the bug. Had the field been declared private final String name = "child";, it would be a constant variable, and javac would replace name with the constant "child" inside describe, so the program would print 5 and seem to work. A final field initialised with anything that is not a compile-time constant, or set in the constructor, is null at that point again. Q10 shows both cases side by side.
8Performance & Production Considerations
- Keep constructors cheap and predictable. Frameworks create objects at startup, in tests and sometimes per request; a constructor that opens connections or reads files makes all of them slow and fragile. Keep construction to checks and assignments (Figure 5).
- Fail at startup, not on the first request. With constructor injection, a missing or misconfigured dependency stops the application while it starts, which is what a deployment pipeline needs to see.
- Some frameworks bypass your constructor. JPA, older Jackson mappings and Java serialisation create objects through a no-argument constructor, or without one, and then set fields by reflection, so the checks in your constructor do not run. Validate again at the boundary, or use records, which Jackson creates through the canonical constructor.
- Safe publication. An object with only final fields, constructed without
thisescaping, can be shared between threads without locks. One that registers itself or starts a thread in its constructor can be seen half-built by another thread.

9Architecture & Design Considerations
Constructors are how dependencies enter a component. Constructor injection — passing all required collaborators as constructor parameters — is the recommended style in Spring and most DI containers: dependencies are explicit, can be final, and the object cannot exist without them. When a constructor needs more than about four or five parameters, it usually signals a class with too many responsibilities rather than a need for a better constructor.
10Interview Questions & Answers
When does the compiler generate a default constructor?
Only when a class declares no constructor at all. It takes no parameters, has the class's access level and calls super().
What is the difference between this() and super() in a constructor?
this(...) calls another constructor of the same class; super(...) calls a superclass constructor. A constructor can call only one of them, and if neither is written the compiler inserts super().
In what order do constructors run in an inheritance chain?
Each constructor first invokes its superclass constructor, up to Object. The bodies then complete from the top down: Object, then the superclass, then the subclass — with each class's field initialisers running just before its own constructor body. Example 2 prints the sequence.
Why is calling an overridable method from a constructor dangerous?
During the superclass constructor, the object is already of the subclass type, so the subclass override runs — but the subclass's fields have not yet been initialised. The override sees nulls or zeros and may fail or behave incorrectly.
What changed about constructors in Java 25?
Flexible constructor bodies (JEP 513) are final: statements can appear before this(...) or super(...) to validate or prepare arguments and assign the class's own fields, as long as they do not use the object under construction.
Why is constructor injection preferred over field injection in Spring?
Dependencies are explicit in the signature, can be final, and the object is fully initialised when constructed. It works without the container in unit tests and makes excessive dependencies visible as long parameter lists.
When would you replace constructors with static factories or a builder?
Static factories when creation needs a descriptive name, caching, or returning a subtype. Builders when there are many optional parameters or construction happens in steps. Keep one validating constructor underneath so every path enforces the same invariants.
Can a constructor be final, static or abstract, and can it return a value?
No to all of them. A constructor is not inherited, so final and abstract would mean nothing, and it always runs on a new object, so it cannot be static. It declares no return type and returns no value; the new expression yields the reference. A method with void in front of the class's name compiles, but it is an ordinary method, not a constructor, a classic source of "why is my constructor never called?" bugs.
A class gains a constructor Customer(String name). Why does new Customer() stop compiling, and why does class VipCustomer extends Customer {} fail too?
The compiler generates a default constructor only when a class declares none. Once Customer(String) exists, there is no Customer() any more, so new Customer() fails. VipCustomer declares no constructor, so it gets a default one whose body is super(), and that call has nothing to bind to. Either declare Customer() explicitly or give VipCustomer a constructor that calls super(name).
What does this program print?
public class CtorQuiz {
static class Base {
Base() { System.out.println("Base sees " + describe()); }
String describe() { return "base"; }
}
static class Child extends Base {
private String name = "child";
private final String label = "fixed";
Child() { System.out.println("Child sees " + describe()); }
@Override String describe() { return name + "/" + label; }
}
public static void main(String[] args) {
new Child();
}
}It prints Base sees null/fixed and then Child sees child/fixed. Base() runs before Child's field initialisers, and the virtual call reaches Child.describe(), where name is still null. label is a final field initialised with a constant, so javac compiles it as the constant "fixed" and it is "set" even then. Once Base() returns, Child's initialisers run and its own constructor sees both values.
What does the Java memory model guarantee about final fields, and how can a constructor break it?
If a constructor assigns a final field and this does not escape before the constructor finishes, every thread that later sees a reference to the object sees that field's value, even if the reference was passed through a data race. That is what makes immutable objects safe to share without locks. The guarantee is lost if the constructor publishes this, for example by registering a listener or starting a thread that uses the object, because another thread can then read the field before it is assigned. Non-final fields never had the guarantee.
After a developer adds a constructor Order(Customer customer) to a JPA entity, the application fails to load orders with "No default constructor for entity". What happened, and what is the right fix?
JPA providers create entities by reflection through a no-argument constructor and then fill the fields. Adding the parameterised constructor removed the compiler-generated default one. Add an explicit no-argument constructor, protected so that application code still has to use the validating constructor, and keep the business constructor for new orders. Remember that objects loaded from the database bypass the business constructor's checks, so the database constraints must enforce the same rules.
Should a domain object validate its arguments in the constructor, or should validation live in a separate layer such as Bean Validation?
Both, for different rules. The constructor enforces invariants that must hold for every instance, whoever creates it: required values, ranges, consistency between fields. Bean Validation at the API boundary checks user input and reports every problem at once with field-level messages, which a constructor throwing on the first error cannot do. Relying only on the boundary lets other code paths create invalid objects; relying only on the constructor gives poor error messages. Keep the two in step with tests.
How would you design object creation for a domain model that many teams and services use?
Make the published types immutable, with one validating constructor per type and named static factories for the common cases, and builders only where there are several optional values. Keep constructors free of I/O and of framework annotations, so that the model can be used in any service and in tests. Put framework needs, such as no-argument constructors for persistence, in adapters or mapping layers rather than in the shared model. Evolve it additively: new factories or optional builder fields keep existing callers compiling, while a changed constructor signature breaks every team at once.
Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.
Key Takeaways
- Constructors establish a valid state; they have no return type.
- Default constructor only when none is declared.
- Every constructor starts with this(...) or super(...); chains end at Object.
- Never call overridable methods or leak this from a constructor.
- Java 25 allows validation before super(...).