Runtime AtlasJava platform fieldbook
Java · Language to RuntimeView Markdown source

Inheritance, interfaces, and sealed hierarchies

Inheritance models an is-a relationship. Composition models has-a and is often more flexible.

Access and inheritance

private members belong to the declaring class. Package-private allows the same package. protected adds subclass access under specific rules. public is visible wherever the type is accessible.

Constructors are not inherited. A subclass constructor invokes a superclass constructor. Overridden instance methods use dynamic dispatch. Static methods are hidden, not overridden. Fields are hidden by name, not polymorphic.

Interfaces

An interface defines a capability contract. It may have abstract, default, static, and private methods. A class can implement multiple interfaces. Default-method conflicts must be resolved explicitly.

Use interfaces at meaningful variability or architectural boundaries. Creating an interface for every class adds ceremony when no alternative or contract exists.

Abstract, final, and sealed

An abstract class can hold shared state and partial implementation. final prevents extension or overriding. A sealed class/interface explicitly permits known direct subtypes; permitted implementations must be final, sealed, or non-sealed.

Sealed hierarchies pair well with exhaustive pattern-matching switch.

sealed interface PaymentResult permits Approved, Declined, Failed {}
record Approved(String id) implements PaymentResult {}
record Declined(String reason) implements PaymentResult {}
record Failed(Throwable cause) implements PaymentResult {}

Liskov principle

A subtype should honor the expectations of its supertype. If callers need special checks before using a subtype, the inheritance model may be wrong.

Feynman check

An interface is a power-socket shape. Different devices may fit it. A sealed interface is a socket for a known approved list of device types.

Runtime AtlasIndependent study material · verify production details in official Java documentation