Lesson 8 of 23

In progress

Course progress

Java

Constructors and object validity

Use constructors to make invalid objects impossible, chain them to avoid repetition, and know why a constructor should not call an overridable method.

A constructor is the only place an object can be set up before anyone uses it. That makes it the natural place to enforce the rules that must hold for the object’s whole life.

What you will learn

  • Validate in the constructor so no invalid object exists.
  • Chain constructors with this(...).
  • Avoid the traps: overridable calls, leaking this, and too many parameters.

The constructor’s job

public class Email {
private final String address;
Email(String address) {
if (address == null || !address.contains("@")) {
throw new IllegalArgumentException("invalid email: " + address);
}
this.address = address.strip().toLowerCase();
}
String address() {
return address;
}
}

After this constructor returns, address is non-null, normalised and contains an @. Every method can rely on that, which removes defensive checks from the rest of the class.

The alternative — a setter that validates — allows an object to exist in an invalid state between creation and the first setter call. Making the field final and validating once is stricter and simpler.

Default and no-argument constructors

If a class declares no constructor, the compiler adds a public no-argument one. Declaring any constructor removes it:

public class Point {
private final int x;
private final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
// new Point() no longer compiles

That is usually what you want: an object that requires coordinates should not be creatable without them. If a no-argument form is meaningful, declare it explicitly with defaults.

Chaining constructors

public class Money {
private final long paise;
private final String currency;
Money(long paise, String currency) {
if (paise < 0) {
throw new IllegalArgumentException("negative amount");
}
this.paise = paise;
this.currency = currency == null ? "INR" : currency;
}
Money(long paise) {
this(paise, "INR");
}
static Money rupees(long rupees) {
return new Money(rupees * 100);
}
}

this(paise, "INR") calls the other constructor, so validation and normalisation live in one place. Duplicating the body in both is how the two drift apart.

A static factory such as rupees names the unit at the call site: Money.rupees(45) is unambiguous where new Money(45) is not. Factories also allow returning a cached instance or a subtype, which a constructor cannot.

Overloading and ambiguity

Money(long paise) { ... }
Money(String currency) { ... }

new Money(100) is clearly the first. But new Money(null) becomes ambiguous, and a constructor with (int) and (long) overloads makes new Money(5) pick the narrower one silently.

Keep overloads to cases where the argument type or count makes the choice obvious. When two overloads could both accept the same call, rename one or use a static factory.

The overridable-method trap

public class Base {
Base() {
print();          // calls the subclass override before the subclass is initialised
}
void print() {
System.out.println("base");
}
}
public class Child extends Base {
private final String name = "child";
@Override
void print() {
System.out.println(name);   // prints null
}
}

The subclass’s field initialisers have not run when the base constructor calls the overridden method, so name is still null. The fix is to avoid calling overridable methods from a constructor; make the method final or private if it must be called.

Leaking this

Passing this to another object from a constructor publishes a partially built object:

Listener.register(this);   // inside the constructor

Another thread or callback can see the object before its fields are set. Finish construction first, then register.

Too many parameters

new Report("sales", "2025-01", "pdf", true, false, 12);

Six positional values, several of them booleans, is unreadable at the call site. Options:

  • A record grouping the related values: new ReportSpec(range, format, options).
  • A builder for optional values:
Report report = Report.builder()
.range("2025-01")
.format("pdf")
.includeCharts(true)
.build();

A builder is worth the code when most calls set only some fields. For three required values, a constructor is simpler.

Copy constructors

Money(Money other) {
this(other.paise, other.currency);
}

A copy constructor makes a distinct object with the same values, which is useful for immutable classes shared across threads and for defensive copies. With records, new Money(m.paise(), m.currency()) is the equivalent.

Constructors and inheritance

A subclass constructor must call a superclass constructor, explicitly with super(...) or implicitly with no arguments. If the parent has no no-argument constructor, the subclass must pass arguments:

class SavingsAccount extends Account {
SavingsAccount(long opening) {
super(opening);
}
}

super(...) must be the first statement. That ordering guarantees the parent’s invariants hold before the child adds its own.

Doing work that can fail in a constructor — calling a network, opening a file — so new can throw and the caller has no object to clean up. Constructors should validate and assign, not perform I/O.

Write a DateRange class with a start and end date as ISO strings, rejecting a start after the end, and a static factory ofDays(int) that produces a range from a start date for n days. Use a record if it fits.

Show solution
public record DateRange(String start, String end) { DateRange { if (start == null || end == null || start.compareTo(end) > 0) { throw new IllegalArgumentException("start must not be after end"); } } static DateRange ofDays(String start, int days) { java.time.LocalDate from = java.time.LocalDate.parse(start); java.time.LocalDate to = from.plusDays(days - 1L); return new DateRange(from.toString(), to.toString()); } int length() { return (int) (java.time.LocalDate.parse(end).toEpochDay() - java.time.LocalDate.parse(start).toEpochDay()) + 1; } }

The compact record constructor validates without repeating the field assignments. ISO strings compare correctly as text, so the ordering check needs no parsing, and the factory computes the end date from a duration rather than making the caller do it.

Recap

  • Validate in the constructor and keep fields final so no invalid object can exist.
  • Chain constructors with this(...) and name units with static factories.
  • Do not call overridable methods or leak this during construction.

Next, encapsulation: getters, setters and the design decisions behind them.

Can a constructor be private?
Yes, which prevents outside instantiation. That is how singletons and static factories control creation.
Do records validate?
Yes, with a compact constructor that throws before the fields are assigned.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.