Skip to content

Chapter 9 of 37

Classes and Objects

Model state and behavior with fields, methods, static members, and object identity.

36 minutes 10 quick checksBy Subha Prasad
Lesson 9 of 37Course navigation

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.

Which statement best describes class?
Which Java term matches this description: A blueprint declaring instance state, behavior, and type-level members.
Which statement best describes object?
Which Java term matches this description: A runtime instance with identity, state, and behavior.
Which statement best describes instance field?
Which Java term matches this description: Per-object state initialized during object construction.
Which statement best describes static member?
Which Java term matches this description: A member associated with the class rather than each instance.
Which statement best describes this?
Which Java term matches this description: A reference to the current receiver object inside an instance context.

0 of 10 checks passed

Your progress is saved on this device.

Classes and Objects | Java Lesson | Subha Prasad