Classes, Objects, Fields, and Constructors

A class defines state and behavior; an object is a runtime instance. Constructors establish valid initial state. Fields should normally be private, with behavior exposed through methods rather than unrestricted mutation.

public final class User {
    private final String id;
    private String displayName;

    public User(String id, String displayName) {
        this.id = id;
        this.displayName = displayName;
    }

    public String id() { return id; }
    public String displayName() { return displayName; }
}

Favor constructors that prevent invalid states. If a field must never change after construction, make it final.

Key Takeaways
  • Constructors should establish invariants.
  • Encapsulation keeps object state under controlled mutation.
  • Prefer immutable fields when the domain allows it.