---
title: "Classes, objects, records, and enums"
chapter: "03"
---

# Classes, objects, records, and enums

A class defines state and behavior. An object is one runtime instance.

## Encapsulation and invariants

Keep fields private. Make invalid states impossible through constructors and
methods. A class should protect its own rules rather than expose setters for
every field.

```java
public final class Account {
  private final String id;
  private BigDecimal balance;

  public void debit(BigDecimal amount) {
    if (amount.signum() <= 0 || balance.compareTo(amount) < 0) {
      throw new IllegalArgumentException("Invalid debit");
    }
    balance = balance.subtract(amount);
  }
}
```

## Constructors and initialization

Instance fields initialize before the constructor body. A constructor may
delegate to another constructor with `this(...)`. Java 25 finalizes flexible
constructor bodies, allowing safe statements before an explicit constructor
invocation under defined rules; keep validation understandable.

## Records

A record is a concise nominal data carrier with final components, accessors,
and generated equality/hash/toString behavior. Use a compact constructor to
validate or normalize. A record is shallowly immutable: a component can still
refer to a mutable list.

## Enums

An enum defines a fixed set of instances and can contain fields, methods, and
constant-specific behavior. Prefer enums to magic strings for closed states.
Use `EnumSet` and `EnumMap` for efficient enum collections.

## Static and instance members

Static members belong to the class; instance members belong to an object.
Global mutable static state harms tests and concurrency. Constants should be
immutable, not merely references marked `final`.

## Feynman check

A class is a blueprint, an object is a house, a record is a labeled immutable
shipping form, and an enum is a fixed set of official status stamps.
