Skip to content

Beginner · Classes and objects · topic 17 of 60 · 25 min

Constructors and this

Explanation

A constructor is a special method with the class's name and no return type that runs when you write new. It sets up a valid object from the start. this.field = field separates a field from a parameter of the same name, constructors can be overloaded, and this(...) calls another constructor. If you write any constructor, Java no longer adds the default no-argument one.

Why constructors?

In the last topic we created an account and then set its fields one by one. It is easy to forget one and end up with an account that has no owner. A constructor runs automatically when the object is created and makes sure it starts in a valid state.

java
public class BankAccount {
    private final String owner;
    private double balance;

    public BankAccount(String owner, double openingBalance) {   // no return type
        if (owner == null || owner.isBlank()) throw new IllegalArgumentException("Owner required");
        if (openingBalance < 0) throw new IllegalArgumentException("Negative opening balance");
        this.owner = owner;              // this.owner = the field; owner = the parameter
        this.balance = openingBalance;
    }
}
BankAccount acc = new BankAccount("Asha", 1000);

this: the field versus the parameter

When a parameter has the same name as a field, the parameter "shadows" the field inside the constructor. owner = owner; would just assign the parameter to itself and leave the field null. this.owner refers to the field of the object being built.

Careful: Writing balance = balance; (without this.) compiles without error and does nothing useful: the field stays 0. If an object's field is mysteriously empty after construction, look for a missing this.

Overloaded constructors and this(...)

java
public class Product {
    private final String name;
    private final double price;
    private int stock;

    public Product(String name, double price, int stock) {
        this.name = name;
        this.price = price;
        this.stock = stock;
    }

    public Product(String name, double price) {
        this(name, price, 0);        // call the 3-argument constructor; must be the first statement
    }
}
Product a = new Product("Pen", 20, 100);
Product b = new Product("Notebook", 60);   // stock 0
Chaining with this(...) keeps the validation and setup in ONE place.

The default constructor

If a class has no constructor at all, the compiler adds an invisible public no-argument constructor that does nothing special. As soon as you write any constructor, that default one is NOT added. Then new Product() no longer compiles unless you write a no-argument constructor yourself.

java
class Box { int size; }
new Box();                 // fine: default constructor exists

class Crate { int size; Crate(int size) { this.size = size; } }
// new Crate();            // compile error: constructor Crate in class Crate cannot be applied to given types

Initialisation order (simplified)

  1. Fields get default values (0, null…).
  2. Field initialisers run in the order written (private int stock = 10;).
  3. The constructor body runs.

Inheritance adds one more step (the parent's constructor runs first), which module 5 covers.

Think of it like this: A constructor is like the admission form at a hospital: a patient cannot get a bed number until the essential fields (name, age, emergency contact) are filled in. Overloaded constructors are like the short form for walk-in patients and the full form for planned admissions; both end in the same registration process.
Tip: Validate arguments in the constructor and throw IllegalArgumentException with a clear message. It is much easier to debug "Owner required" at creation time than a mysterious null ten method calls later.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Constructors and this · 1/6

Constructors

In this lesson you will make sure every object starts in a valid state, using constructors.

Prefer a video by a teacher? Find free videos on “java constructors this keyword constructor chaining overloading” on YouTube ↗

In real life: Creating train bookings

A ticket system creates a Booking with the PNR, passenger name and train number. A second constructor generates a PNR automatically when none is given. Both run the same checks through this(...).

java
class Booking {
    private static int nextPnr = 4_521_000;
    private final String pnr, passenger;
    private final int train;

    Booking(String pnr, String passenger, int train) {
        if (passenger == null || passenger.isBlank()) throw new IllegalArgumentException("Passenger name required");
        this.pnr = pnr; this.passenger = passenger; this.train = train;
    }
    Booking(String passenger, int train) {
        this(String.valueOf(nextPnr++), passenger, train);
    }
}

Practice (0/3 done)

Task 1 · Question

What does this print? class P { int x; P(int x) { x = x; } } … System.out.println(new P(5).x);

Task 2 · Question

class Car { Car(String model) { … } } Which line does NOT compile?

Task 3 · Practice

Write a class Product with private final fields name and price and a private int stock. Add a 3-argument constructor that rejects a blank name, a negative price or negative stock with IllegalArgumentException, and a 2-argument constructor that chains to it with stock 0. Create one valid product and try to create an invalid one inside try/catch.

Quick quiz

Question 1

1.What is the return type of a constructor?

Question 2

2.Where must this(...) appear in a constructor?

Question 3

3.When does Java add a default no-argument constructor?

Question 4

4.What is the main job of a constructor?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What is the return type of a constructor?

Answer: It has none

Constructors have no return type, not even void.

Where must this(...) appear in a constructor?

Answer: As the first statement

A constructor call must be the first statement.

When does Java add a default no-argument constructor?

Answer: Only when the class declares no constructor at all

Writing any constructor removes the default one.

What is the main job of a constructor?

Answer: To put a new object into a valid initial state

Constructors initialise objects.

What does : this(name, 0m) after a constructor header do?Related

Answer: Calls another constructor of the same class first

It chains to another constructor to reuse its setup code.

From Classes, objects and constructors

Why do Flutter widgets often use const constructors?Related

Answer: Constant widgets are created once and can be skipped during rebuilds

const saves work at run time.

From Classes and constructors

Why mark a one-argument constructor explicit?Related

Answer: To stop silent implicit conversions from that argument type

explicit prevents surprises such as passing 42 where a Counter is expected.

From Constructors and destructors

Is Java pass-by-value or pass-by-reference?Related

Answer: Always pass-by-value (references are copied for objects)

Java copies every argument; for objects, the copy is the reference.

From Methods: parameters, return values and overloading

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 3 more topics in “Classes and objects” before its exam: Encapsulation: private fields, getters and setters, static members and final, toString, equals, hashCode and records.
  2. Module 4 exam: Classes and objects · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Inheritance, polymorphism and interfaces. 60 topics left in the course before the final exam.

← Previous: Classes and objects