Lesson content
Read, practise, then check your understanding
A class defines fields, methods, constructors, nested types, and initialization behavior. Each object has identity and instance state; static members belong to the class. Keep fields private and expose operations that preserve invariants.
A focused model
public final class BankAccount {
private final String owner;
private long balanceCents;
public BankAccount(String owner, long openingCents) {
this.owner = Objects.requireNonNull(owner);
if (openingCents < 0) throw new IllegalArgumentException();
balanceCents = openingCents;
}
public void deposit(long cents) {
if (cents <= 0) throw new IllegalArgumentException();
balanceCents = Math.addExact(balanceCents, cents);
}
}
this refers to the receiver. Static factories can name construction choices and return subtypes. Override equals and hashCode together for value semantics; provide a useful toString without secrets. Records are concise immutable data carriers but still need invariant validation. Favor composition and single-purpose classes.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.