Java Materials
← Core Java · Chapter 2

Object-oriented design and lifecycle

Encapsulation protects invariants, abstraction exposes meaningful capabilities, and polymorphism lets implementations vary behind a contract. Inheritance is useful for true substitutability. Composition and delegation make collaborators replaceable without inheriting an entire implementation. Interface defaults can evolve behavior, but conflicts need an explicit resolution when neither default is more specific.

Dispatch, overloads and default methods

Definition:

Overload selection chooses the callable signature; dynamic dispatch chooses its overriding implementation.

Explanation:

Overload resolution runs at compilation, while an applicable instance override dispatches at runtime.

Illustration image:

Dispatch, overloads and default methods. Declared reference type · Selected signature · Actual receiver class · Overriding methodDispatch, overloads and default methodsSource or actorDeclared reference typeFirst boundarySelected signatureInspected stateActual receiver classObservable effectOverriding method
Declared reference type · Selected signature · Actual receiver class · Overriding method

Example:

Worked Java example · see surrounding context in notes
static String select(long v) { return "widen"; }
static String select(Integer v) { return "box"; }
// select(1) returns "widen".

Expected behavior. The literal is int, so the primitive-widening overload is found before a boxing invocation is needed.

Internal working:

Widening can win before boxing; varargs is a later applicability phase. Static methods and fields do not participate in dynamic dispatch. A class implementation wins over an inherited interface default, and independent conflicting defaults need an override.

Interview questions:

Which happens first for a Number reference holding an Integer?

The compiler selects the overload using declared types; runtime dispatch then selects the receiver’s override of that signature.

Initialization and constructor escape

Definition:

Object initialization sets up fields and executes constructor code according to the superclass hierarchy.

Explanation:

A virtual call from a superclass constructor can invoke a subclass override before subclass fields are initialized.

Illustration image:

Initialization and constructor escape. Allocated field: null · Base constructor active · Child override sees null · Child field becomes readyInitialization and constructor escapeSource or actorAllocated field: nullFirst boundaryBase constructor activeInspected stateChild override sees nullObservable effectChild field becomes ready
Allocated field: null · Base constructor active · Child override sees null · Child field becomes ready

Example:

Worked Java example · see surrounding context in notes
class Base { Base() { inspect(); } void inspect() {} }
class Child extends Base {
    private final String name = "ready";
    @Override void inspect() { System.out.println(name); }
}
// new Child() prints null.

Expected behavior. The subclass override is selected, but the field initializer has not run.

Internal working:

The same danger occurs when a constructor registers this as a listener or submits it to a worker. Wire callbacks after construction and use a safe publication boundary when passing an object to other threads.

Interview questions:

Why might a subclass field be null in a superclass constructor call?

The override can run before the subclass initializer assigns that field.

Immutability, records and sealed contracts

Definition:

An immutable object preserves its observable value after construction.

Explanation:

A record accessor can still expose mutable state if it returns a shared mutable component.

Illustration image:

Immutability, records and sealed contracts. Caller mutable list · Compact constructor · Unmodifiable snapshot · Shared elements if mutableImmutability, records and sealed contractsSource or actorCaller mutable listFirst boundaryCompact constructorInspected stateUnmodifiable snapshotObservable effectShared elements if mutable
Caller mutable list · Compact constructor · Unmodifiable snapshot · Shared elements if mutable

Example:

Worked Java example · see surrounding context in notes
sealed interface Result permits Accepted, Rejected {}
record Accepted(java.util.List<String> ids) implements Result {
    Accepted { ids = java.util.List.copyOf(ids); }
}
record Rejected(String reason) implements Result {}

Expected behavior. The family has two permitted direct alternatives. Changes to the caller’s original list do not change Accepted.

Internal working:

List.copyOf protects structure, not the objects inside. Copy nested mutable values individually when the ownership contract requires a snapshot. Sealed families model known cases; interfaces and delegation are better when external extension is part of the design.

Interview questions:

Does a record with a List field guarantee deep immutability?

No. Freeze list structure when needed and independently copy mutable elements if their state belongs to the snapshot.

Reference subtopics

Dispatch and overloads

Overloading is chosen using compile-time types through strict invocation, boxing-compatible invocation and then varargs as applicable. Widening can win over boxing. null can make unrelated reference overloads ambiguous. Overridden instance methods dynamically dispatch using the receiver; fields and static methods are selected by declaration context. Covariant returns narrow the return type of an override.

Initialization, this and super

Class initialization establishes superclass static state before subclass static initialization. Instance construction delegates with this or super; superclass construction runs before subclass instance field initializers and constructor body. An overridable method called from a constructor can see uninitialized subclass state. Do not publish this before the invariant holds. final prevents reassignment, overriding or subclassing depending on placement.

Nested classes and domain types

A static nested class has no enclosing instance. An inner class can retain the enclosing instance; local and anonymous classes can capture effectively final values. Enums model finite identities. Records describe component-based values, while sealed classes and interfaces constrain direct subtypes. A non-sealed permitted type reopens its branch.

Immutability and copying

Use private state, validate in constructors and copy mutable inputs and outputs according to ownership. A shallow copy duplicates the outer container, not its elements. A deep copy recursively isolates mutable state. A final List reference can still point at a mutable list; a record has shallow component immutability and may need a compact constructor.

Run the complete Java labs ↗ · Java reference ↗