JAVA-102 · Lesson 3 of 12 · 23 min
Constructors and object initialization
▶ Video coming soon A video version of this lesson is on the way.
By the end of lesson 2 the booking system's classes protected their fields, but building objects had become awkward. A repair booking needs a customer, a bike, a date and a job, and usually a price; a walk-in booking has no date yet; a booking copied from last year's tune-up needs most of the same details. The plan for Wednesday, January 27, 2027 is to look closely at constructors: how to offer several ways to build an object, how to avoid repeating code between them, and exactly what Java does, step by step, when new runs.
What a constructor must do
A constructor's job is to leave a new object in a valid state, with every invariant true. When the constructor finishes, the object should be ready to use; no caller should have to remember to call a setUp method afterwards. That means a constructor should take the values the object cannot do without, check them, and give every other field a sensible starting value.
public class Main {
public static void main(String[] args) {
Bike b = new Bike("Raleigh", "Cadent 2", 54, "RL2271940");
System.out.println(b);
Bike bad = new Bike("Trek", "FX 2", 0, "");
System.out.println(bad);
}
}
class Bike {
private final String make;
private final String model;
private final int frameCm;
private final String serial;
Bike(String make, String model, int frameCm, String serial) {
this.make = make.strip();
this.model = model.strip();
this.frameCm = (frameCm >= 30 && frameCm <= 66) ? frameCm : 0;
this.serial = serial.isBlank() ? "UNRECORDED" : serial.strip().toUpperCase();
}
@Override
public String toString() {
String size = frameCm == 0 ? "size unknown" : frameCm + " cm";
return make + " " + model + ", " + size + ", serial " + serial;
}
}Raleigh Cadent 2, 54 cm, serial RL2271940 Trek FX 2, size unknown, serial UNRECORDED
What this code does
The constructor cleans and checks every value before storing it, so a Bike is always in a known state. A frame size outside 30 to 66 cm becomes 0, meaning unknown, and a blank serial number is stored as UNRECORDED. Lesson 8 shows how a constructor can refuse bad values outright by throwing an exception.
Overloaded constructors
A class may have several constructors, as long as their parameter lists differ in number or types. This is constructor overloading, the same idea as method overloading in JAVA-101 lesson 8. Java picks the constructor whose parameters match the arguments of the new expression. Overloading lets callers supply only what they know: a booking with a date, or a walk-in booking without one.
public class Main {
public static void main(String[] args) {
Booking a = new Booking("Ana Ruiz", "brake bleed", "2027-01-30", 4500);
Booking b = new Booking("Theo Park", "flat repair");
System.out.println(a);
System.out.println(b);
}
}
class Booking {
private final String customer;
private final String job;
private final String date;
private final long priceCents;
Booking(String customer, String job, String date, long priceCents) {
this.customer = customer;
this.job = job;
this.date = date;
this.priceCents = priceCents;
}
Booking(String customer, String job) {
this.customer = customer;
this.job = job;
this.date = "walk-in";
this.priceCents = 0;
}
@Override
public String toString() {
return date + ": " + customer + ", " + job + (priceCents > 0 ? ", quoted " + priceCents + " cents" : ", to be quoted");
}
}2027-01-30: Ana Ruiz, brake bleed, quoted 4500 cents walk-in: Theo Park, flat repair, to be quoted
What this code does
Booking has two constructors, and Java chooses between them by the number of arguments. The second one is for walk-ins and fills in a date of walk-in and a price of 0. Both constructors assign the same final fields, which is repetition the next section removes.
Chaining constructors with this(...)
Repeating the assignments in every constructor invites mistakes: add a check to one and forget the other, and the two ways of building a booking behave differently. Java lets one constructor call another of the same class with this(...) as its very first statement. The usual pattern is to put all the real work in the constructor with the most parameters and have the shorter ones pass default values to it.
public class Main {
public static void main(String[] args) {
System.out.println(new Booking("Ana Ruiz", "brake bleed", "2027-01-30", 4500));
System.out.println(new Booking("Theo Park", "flat repair"));
System.out.println(new Booking("Mei Lin", "full tune-up", "2027-02-06"));
}
}
class Booking {
private final String customer;
private final String job;
private final String date;
private final long priceCents;
Booking(String customer, String job, String date, long priceCents) {
if (priceCents < 0) priceCents = 0;
this.customer = customer.strip();
this.job = job.strip();
this.date = date;
this.priceCents = priceCents;
}
Booking(String customer, String job, String date) {
this(customer, job, date, 0);
}
Booking(String customer, String job) {
this(customer, job, "walk-in");
}
@Override
public String toString() {
return date + ": " + customer + ", " + job + (priceCents > 0 ? ", " + priceCents + " cents" : ", to be quoted");
}
}2027-01-30: Ana Ruiz, brake bleed, 4500 cents walk-in: Theo Park, flat repair, to be quoted 2027-02-06: Mei Lin, full tune-up, to be quoted
What this code does
Each shorter constructor passes a default to the next longer one with this(...), so all checks and assignments live in the four-parameter constructor. The two-parameter walk-in constructor calls the three-parameter one, which calls the full one. Changing a rule now means changing one place.
Two rules apply to this(...). It must be the first statement in the constructor, and a constructor may call this(...) or super(...), which lesson 5 introduces, but not both. Java 25 relaxes the first rule a little with flexible constructor bodies, which allow some statements before the call; this course keeps the classic form, which every Java version accepts.
Default values and field initializers
Fields that a constructor does not assign are not left random. Java gives every field a default value before any of your code runs: 0 for numbers, false for boolean, '\u0000' for char and null for references. Local variables inside methods do not get defaults, which is why javac insists you assign them, but fields always do.
You can also give a field a starting value where it is declared, such as private String status = "REQUESTED";. That is a field initializer. It runs for every constructor, which makes it the right place for a starting value that never depends on constructor arguments.
The order of initialization
When new runs, Java builds the object in a fixed order. Knowing the order explains many puzzling bugs, such as a field that is still 0 when a method expects it to be set.
public class Main {
public static void main(String[] args) {
System.out.println("Creating a booking");
Booking b = new Booking("Ana Ruiz");
System.out.println("Done: " + b.describe());
}
}
class Booking {
private String status = trace("field initializer sets status", "REQUESTED");
private final String customer;
private int reminders;
{
trace("instance initializer block runs", "");
reminders = 1;
}
Booking(String customer) {
trace("constructor body runs, reminders = " + reminders, "");
this.customer = customer;
}
private static String trace(String message, String value) {
System.out.println(" " + message);
return value;
}
String describe() {
return customer + " " + status + ", reminders " + reminders;
}
}Creating a booking field initializer sets status instance initializer block runs constructor body runs, reminders = 1 Done: Ana Ruiz REQUESTED, reminders 1
What this code does
The printed lines show the order: the field initializer runs first, then the instance initializer block in braces, then the constructor body. By the time the constructor body runs, reminders already holds 1 because the block set it. Instance initializer blocks are rare in real code, but they make the order easy to see.
Lesson 5 adds one more step for classes that extend another class: the parent's part of the object is built first, before any of these steps for the child.
final fields must be assigned exactly once
A final field must receive a value exactly once, either in its initializer or in every constructor, and javac checks this. If any path through a constructor leaves a final field unassigned, or assigns it twice, the class does not compile.
public class Main {
public static void main(String[] args) {
System.out.println(new Slot(9).hour);
}
}
class Slot {
final int hour;
final String date;
Slot(int hour) {
this.hour = hour;
}
}What this code does
The Slot constructor assigns hour but forgets date, a final field with no initializer. javac refuses the class and names the field that might not have been initialized. Assigning date in the constructor, perhaps through this(...) from a constructor that takes a date, fixes it.
$ javac Main.java
Main.java:13: error: variable date might not have been initialized
}
^
1 errorStatic factory methods
Lesson 2's Money class had a private constructor and a static method, ofCents, that built the object. Such static factory methods have three advantages over plain constructors. They have names, so Money.ofDollars(85) and Money.ofCents(8500) are both clear where two constructors with one long parameter could not even coexist. They can return an existing object instead of a new one. And they can check arguments and choose a sensible result. Java's library is full of them: List.of, LocalDate.of, Integer.valueOf.
public class Main {
public static void main(String[] args) {
Duration a = Duration.ofMinutes(90);
Duration b = Duration.ofHours(2);
Duration c = Duration.parse("1h45m");
System.out.println(a + ", " + b + ", " + c);
System.out.println("Total: " + a.plus(b).plus(c));
}
}
final class Duration {
private final int minutes;
private Duration(int minutes) {
this.minutes = Math.max(0, minutes);
}
static Duration ofMinutes(int minutes) { return new Duration(minutes); }
static Duration ofHours(int hours) { return new Duration(hours * 60); }
static Duration parse(String text) {
int h = text.indexOf('h');
int hours = Integer.parseInt(text.substring(0, h));
int mins = Integer.parseInt(text.substring(h + 1, text.length() - 1));
return new Duration(hours * 60 + mins);
}
Duration plus(Duration other) { return new Duration(minutes + other.minutes); }
@Override
public String toString() {
return (minutes / 60) + "h" + String.format("%02d", minutes % 60) + "m";
}
}1h30m, 2h00m, 1h45m Total: 5h15m
What this code does
Three named factory methods build the same kind of object from minutes, hours or a short text. Because the constructor is private, these are the only ways in, and each one makes its meaning clear at the call. The class is immutable, so plus returns a new Duration rather than changing either one.
Java has its own java.time.Duration, which JAVA-230 uses; this small version only shows the pattern. Name factory methods with the library's conventions: of for building from parts, parse for reading text, from for converting another type and valueOf for simple conversions.
Copy constructors
Sometimes you want a new object that starts as a copy of an existing one, such as next year's tune-up booking based on this year's. A copy constructor takes an object of the same class and copies its fields, with any changes made afterwards through methods. For immutable classes no copy is needed, but for a class with mutable state it is the clearest way to make an independent duplicate.
public class Main {
public static void main(String[] args) {
Booking last = new Booking("Mei Lin", "full tune-up", "2026-04-11");
last.addNote("rear derailleur hanger bent");
Booking next = new Booking(last, "2027-04-10");
next.addNote("check hanger again");
System.out.println(last);
System.out.println(next);
}
}
class Booking {
private final String customer;
private final String job;
private final String date;
private String notes = "";
Booking(String customer, String job, String date) {
this.customer = customer;
this.job = job;
this.date = date;
}
Booking(Booking other, String newDate) {
this(other.customer, other.job, newDate);
this.notes = other.notes;
}
void addNote(String note) {
notes = notes.isEmpty() ? note : notes + "; " + note;
}
@Override
public String toString() {
return date + " " + customer + ", " + job + " [" + notes + "]";
}
}2026-04-11 Mei Lin, full tune-up [rear derailleur hanger bent] 2027-04-10 Mei Lin, full tune-up [rear derailleur hanger bent; check hanger again]
What this code does
The copy constructor builds a new booking from an old one with a new date, reusing the main constructor through this(...). It copies the notes, so next starts with last year's note, and adding a note to next leaves last unchanged. A constructor may read the private fields of another object of the same class.
That last point surprises many people: private means private to the class, not to the object. Code inside Booking may read other.customer because it is Booking code, even though other is a different object.
The builder pattern, briefly
When a class has many optional values, even chained constructors become hard to read: new RentalBooking("Ana", bike, 3, true, false, 2000) tells the reader nothing about what true and false mean. The builder pattern offers a separate object with one named method per value and a build method at the end. Libraries use it widely, and you will meet it in Spring Boot in Year 2.
public class Main {
public static void main(String[] args) {
Rental r = new Rental.Builder("Ana Ruiz", "City bike 4")
.days(3)
.helmet(true)
.depositCents(5000)
.build();
System.out.println(r);
System.out.println(new Rental.Builder("Theo Park", "Cargo bike 1").build());
}
}
final class Rental {
private final String customer;
private final String bike;
private final int days;
private final boolean helmet;
private final long depositCents;
private Rental(Builder b) {
customer = b.customer;
bike = b.bike;
days = b.days;
helmet = b.helmet;
depositCents = b.depositCents;
}
@Override
public String toString() {
return customer + ": " + bike + ", " + days + " day(s)" + (helmet ? ", helmet" : "") + ", deposit " + depositCents + " cents";
}
static class Builder {
private final String customer;
private final String bike;
private int days = 1;
private boolean helmet;
private long depositCents = 2500;
Builder(String customer, String bike) {
this.customer = customer;
this.bike = bike;
}
Builder days(int d) { days = Math.max(1, d); return this; }
Builder helmet(boolean h) { helmet = h; return this; }
Builder depositCents(long c) { depositCents = c; return this; }
Rental build() { return new Rental(this); }
}
}Ana Ruiz: City bike 4, 3 day(s), helmet, deposit 5000 cents Theo Park: Cargo bike 1, 1 day(s), deposit 2500 cents
What this code does
The Builder starts with the two values every rental needs and sensible defaults for the rest. Each named method sets one value and returns the builder itself, so calls can be chained, and build creates the immutable Rental. The second rental uses every default: one day, no helmet and a 25-dollar deposit.
Builder is a static nested class, a class declared inside another. Lesson 4 explains static nested classes. Records, in lesson 9, are often an even simpler choice when a class has only a handful of required values.
Try it yourself
Chained constructors
Give Slot a second constructor Slot(String date) that creates a 9 o'clock slot by calling the first constructor with this(...).
The program should print 2027-02-06 at 14:00 and 2027-02-13 at 9:00.
public class Main {
public static void main(String[] args) {
System.out.println(new Slot("2027-02-06", 14));
System.out.println(new Slot("2027-02-13", 14));
}
}
class Slot {
private final String date;
private final int hour;
Slot(String date, int hour) {
this.date = date;
this.hour = hour;
}
@Override
public String toString() {
return date + " at " + hour + ":00";
}
}Try it yourself
A named factory
Add two static factory methods to Price: ofDollars(long dollars) and ofCents(long cents), and make the constructor private.
Use them so the program prints 85.00, 12.99 and 97.99.
public class Main {
public static void main(String[] args) {
Price a = new Price(85);
Price b = new Price(1299);
System.out.println(a);
System.out.println(b);
System.out.println(a.plus(b));
}
}
class Price {
private final long cents;
Price(long cents) {
this.cents = cents;
}
Price plus(Price other) {
return new Price(cents + other.cents);
}
@Override
public String toString() {
return String.format("%d.%02d", cents / 100, cents % 100);
}
}Common mistakes
MistakeGiving a constructor a return type such as void.
InsteadConstructors have no return type; with one, the method is an ordinary method and new uses the default constructor instead.
MistakeCopying the same checks into every overloaded constructor.
InsteadPut the work in one constructor and have the others call it with this(...).
MistakeWriting statements before this(...) in a constructor.
InsteadIn classic Java, this(...) must be the first statement.
MistakeLeaving a final field unassigned on some path through a constructor.
InsteadAssign every final field exactly once in every constructor, or in its initializer.
MistakeCalling new Rental("Ana", bike, 3, true, false, 2000) with unexplained booleans.
InsteadUse a builder or a record with named methods so each value is clear.
Summary and key terms
- A constructor must leave a new object valid, taking the values it cannot do without, checking them and giving every other field a sensible start.
- Constructors can be overloaded by parameter list, and one constructor can call another with this(...) as its first statement, so all the work lives in one place.
- Fields get default values before any code runs, field initializers run for every constructor, and the order is defaults, then initializers and initializer blocks in source order, then the constructor body.
- A final field must be assigned exactly once on every path.
- Static factory methods such as ofCents give construction a name and work well with a private constructor.
- A copy constructor builds an independent duplicate, and private access applies to the whole class, not one object.
- The builder pattern suits classes with many optional values.
- Constructor
- Code that runs when an object is created and gives it a valid starting state.
- Constructor overloading
- Declaring several constructors with different parameter lists.
- Constructor chaining
- One constructor calling another of the same class with this(...).
- Default value
- The value Java gives a field before any code runs: 0, false or null.
- Field initializer
- A value given to a field where it is declared.
- Instance initializer block
- A block of code in braces inside a class that runs for every new object.
- Static factory method
- A named static method that creates objects, often used with a private constructor.
- Copy constructor
- A constructor that makes a new object from an existing one of the same class.
- Builder pattern
- A design in which a separate object collects values step by step and then builds the result.
- Static nested class
- A class declared inside another class with the word static.
Practice problems
Work each problem on paper first, then reveal the answer to check.
What must be true when a constructor finishes?
Show answer
The object is in a valid state with every invariant true.
Where must this(...) appear in a constructor?
Show answer
As the first statement.
What value does a field of type int have before the constructor body runs, if nothing else assigns it?
Show answer
0, its default value.
Name two advantages of static factory methods.
Show answer
They have descriptive names, and they can check arguments or return an existing object.
Why can Booking's copy constructor read other.customer when customer is private?
Show answer
private applies to the whole class, so any Booking code can read the fields of any Booking.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.