Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 08 / Topic 2 of 12

Constructors and this

A constructor is a special method, named exactly like the class, that runs once when new builds an object. It is where you require the information an object cannot do without, and where you can reject bad data before the object even exists. Think of it as the one moment a bank clerk can refuse to open an account — once the account exists, it is too late to say "that opening balance was never valid."

Real-world example: a Wallet that insists on a non-negative opening balance.

static class Wallet {
    String owner;
    double balance;

    Wallet(String owner, double openingBalance) {
        if (openingBalance < 0) {
            throw new IllegalArgumentException("opening balance cannot be negative: " + openingBalance);
        }
        this.owner = owner;
        this.balance = openingBalance;
    }

    Wallet(String owner) {
        this(owner, 0.0);              // chains to the two-argument constructor above
    }

    void addMoney(double amount) {
        this.balance = this.balance + amount;   // "this." is optional here, written for clarity
    }
}
Asha opens with ₹1000.0
Ravi opens with ₹0.0
Asha after addMoney(250): ₹1250.0
rejected: opening balance cannot be negative: -500.0

this is the current object — the one the method or constructor was called on. You need it whenever a parameter and a field share a name (this.owner = owner; means "the field" on the left, "the parameter" on the right); without this., owner = owner; would just reassign the parameter to itself and the field would stay unset. A class can have more than one constructor (overloading, same idea as overloaded methods from Part 5); this(...) as the first line of a constructor calls another constructor in the same class instead of repeating its logic.

Full program: examples/ConstructorsAndThis.java.

Done here? The practice set for Part 8 — including the solutions — is on the part page.

Search the guide