Intermediate 8 min

Constructors and encapsulation

A constructor gives a new object its starting state, and private fields let the class protect that state.

How it works

When new Pass(3) is evaluated, the constructor receives 3 as a parameter. this.balance = balance saves that parameter in the new object’s field. A later call to hoursLeft reads the saved field, while a different pass can hold a different balance.

Walk through an example

A parking pass can begin with a balance set in its constructor. A method such as useOneHour() can check the balance before spending it.

What to watch for

Do validation at the point where state changes. Public fields allow callers to bypass those checks.

Code example

public class Main {
    static class Pass {
        private int balance;

        Pass(int balance) {
            if (balance < 0) throw new IllegalArgumentException("Negative balance");
            this.balance = balance;
        }

        int hoursLeft() { return balance; }
    }

    public static void main(String[] args) {
        System.out.println(new Pass(3).hoursLeft());
    }
}

Check your understanding

Where should you reject an initial balance of -1?

See the example and explanation
Worked example
Given A pass requires a nonnegative balance.
Answer In the constructor.

Every pass starts through its constructor, so the rule is enforced from the moment the object exists.

Open practice problem
Next lessonInterfaces and polymorphism