Objects, Classes & OOP Design

Object Creation & Initialization

Constructors initialize objects, but they are not the only way to get one — static factory methods and builders often serve callers better. Know the initialization order, and reach for a builder when parameters pile up.
  • No constructor written → compiler provides a no-arg constructor; write any → it disappears
  • Static factories beat constructors: they have names, can cache, and can return subtypes (EJ 1)
  • Builder pattern for many/optional parameters (EJ 2)
  • Initialization order: field initializers & init blocks in source order, then the constructor body
  • this(...) chains to another constructor of the same class

Initialization order

When new runs: fields get default values → field initializers and instance initializer blocks execute in source order → the constructor body runs. Static fields/blocks run once, when the class is first loaded (see Class Loading). Overloaded constructors can delegate with this(...) as the first statement — one master constructor avoids duplication.

Constructor chaining
public class Session {
    private final String id;
    private final Duration timeout;

    public Session(String id, Duration timeout) {
        this.id = Objects.requireNonNull(id);
        this.timeout = timeout;
    }

    public Session(String id) {
        this(id, Duration.ofMinutes(30));   // delegate to the master constructor
    }
}
Sources
  • Core Java, Volume I: Fundamentals (13th ed.)Ch. 4.6 — Object Construction
  • Effective Java (3rd ed.)Items 1–5, 8, 9
  • Learning Java (6th ed.)Ch. 5 — Objects in Java