Kotlin OOP Patterns

Kotlin OOP Patterns in Kotlin: Walk onto the floor of an injection-molding shop and the central object is the mold -- a hardened steel tool whose cavity holds…

The Analogy: The Injection-Molding Shop

Walk onto the floor of an injection-molding shop and the central object is the mold -- a hardened steel tool whose cavity holds the exact shape of the part it makes. You clamp the mold into the press, inject molten plastic, and out pops a part. Press again and another identical part appears, and another, each one conforming to the same cavity geometry the mold was cut with. The mold is defined once and stamps out parts without limit. A class is that steel tool: you describe its fields and methods a single time, and from it you press out object after object, every one built to the same specification.

By default this shop seals every mold it builds. The cavity block is hardened and pinned so that no machinist can later bolt an extra insert onto it or grind a new feature into its face. If the shop wants a variant product line, it must order the mold constructed from the start on an open bolster -- a frame with dovetail slots ready to accept inserts. A derived mold bolts new cavity inserts into those slots, adding features while reusing the base geometry it was built on. This is exactly Kotlin's stance: classes are final by default, and only a class marked open will accept a subclass that extends or overrides its behaviour.

Some tools never ship complete. A jig arrives with its bolster and guide pins in place but the cavity itself is a blank plate stamped "insert required." You cannot mount it in the press and make parts as it stands; a downstream shop must supply the missing cavity insert first. That is an abstract class with an abstract member -- it defines the frame but leaves a hole that a concrete subclass is obligated to fill before any object can be made. And when you do swap in your own insert to replace an inherited one, the shop makes you file an override traveler tag; the QA bench rejects any insert change that is not tagged. Kotlin enforces the same discipline with the mandatory override keyword.

The classic ruin on this floor is the apprentice who grabs a sealed, pinned mold and tries to grind a "quick variant" cavity into its hardened face. The block cracks under the cutter and the entire tool is scrapped. Kotlin stops you before the crack ever happens: subclassing a final class is a compile error caught at the bench, not a fracture discovered mid-run. The opposite waste is the manager who orders every mold built open "just in case" -- inviting uncontrolled bolt-ons that no one validated, leaving a floor full of fragile base tools that cannot be adjusted later without shattering every variant welded onto them.


Syntax or Core Structure

A Kotlin class declares its state and behaviour in one place. The primary constructor sits on the class header; val/var in that header both declare and initialise properties. A class is final unless you mark it open, and a subclass must use override on any member it replaces.

open class Tool(val name: String, val weightGrams: Int) {
    open fun describe(): String = name + " (" + weightGrams + "g)"
}

class Insert(name: String, weightGrams: Int, val cavities: Int)
    : Tool(name, weightGrams) {
    override fun describe(): String =
        super.describe() + " with " + cavities + " cavities"
}

fun main() {
    val base: Tool = Tool("bolster", 4000)
    val derived: Tool = Insert("gate-block", 1200, 4)
    println(base.describe())
    println(derived.describe())
}

Output:

bolster (4000g)
gate-block (1200g) with 4 cavities

Tool is declared open, so Insert may extend it; describe is declared open, so Insert may override it. The Insert header passes name and weightGrams up to Tool(name, weightGrams) and declares one new property, cavities. Inside the overriding describe, super.describe() runs the base version to reuse its formatting, then appends the cavity count. Both variables are typed as Tool, but the call dispatches to each object's actual class -- base runs Tool.describe, derived runs Insert.describe. That is virtual dispatch: the runtime type, not the declared type, selects the method.


Technical Depth: Modifiers, Abstraction, and Dispatch

The class and member modifiers

Kotlin's inheritance keywords each carry one precise meaning. The table below is the vocabulary you reach for when deciding how open a tool should be.

ModifierApplies toCan be instantiated?Can be subclassed / overridden?
final (default)class or memberclass: yesno
openclass or memberclass: yesyes
abstractclass or memberclass: nomust be
sealedclassnoonly in same module/file
final overrideoverriding membern/astops further override

The default is final precisely so that inheritance is a deliberate choice, not an accident. You cannot mark a member open unless its class is also open or abstract -- an open method on a sealed tool would be a contradiction the compiler rejects.

Abstract members must be filled

An abstract class can declare a member with no body; any concrete subclass is obligated to supply one. The blank-plate jig cannot run until its cavity is inserted.

abstract class Fastener {
    abstract fun torqueNm(): Int
    fun report(): String = "torque " + torqueNm() + " Nm"
}

class Bolt(private val grade: Int) : Fastener() {
    override fun torqueNm(): Int = grade * 5
}

fun main() {
    val f: Fastener = Bolt(grade = 8)
    println(f.report())
}

Output:

torque 40 Nm

Fastener cannot be instantiated directly -- Fastener() alone would not compile. Bolt supplies the required torqueNm, so it is concrete and can be built. Notice that the non-abstract report calls the abstract torqueNm: the base defines the workflow and the subclass fills the hole. With grade = 8, torqueNm returns 40 and report frames it as "torque 40 Nm".

final override seals a branch

An override is itself open by default -- a sub-subclass could override it again. Prefix it with final to stop the chain at that level.

open class A {
    open fun step(): String = "A"
}
open class B : A() {
    final override fun step(): String = "B"
}
class C : B() {
    // override fun step() here would not compile: B sealed it
    fun label(): String = step() + "-from-C"
}

fun main() {
    println(C().label())
}

Output:

B-from-C

B overrides step and marks that override final, so C inherits B's version and cannot replace it. C.label therefore calls B.step, yielding "B", and appends "-from-C". final override is the tool for locking a specific behaviour partway down a hierarchy while leaving the rest of the class open.

Properties dispatch virtually too

Overriding is not limited to methods. An open val can be replaced by a subclass, and reading it goes through the same virtual dispatch a method call does -- the runtime type decides which property is read, even through a base-typed reference.

open class Node {
    open val label: String = "node"
    fun tag(): String = "<" + label + ">"
}

class Leaf : Node() {
    override val label: String = "leaf"
}

fun main() {
    val n: Node = Node()
    val l: Node = Leaf()
    println(n.tag())
    println(l.tag())
}

Output:

<node>
<leaf>

The non-overridable tag method reads label in both cases, but label is open and Leaf overrides it. When tag runs on the Leaf instance, the property read dispatches to Leaf.label and yields "leaf", so tag returns "<leaf>". Through the Node-typed n, the same code reads Node.label and returns "<node>". A subclass can specialise data as well as behaviour, and both resolve on the actual runtime type.


Real World Example: A Dashboard Panel Registry

A monitoring dashboard registers every panel as it is created, logging a one-line summary so operators can see the layout building up. The base Panel writes that log line from its init block by calling an open summary, and a Gauge subclass refines both the panel's kind and the summary format to include its measurement unit.

open class Panel(val title: String) {
    open val kind: String = "generic"

    init {
        println("registering panel: " + summary())
    }

    open fun summary(): String = title + " [" + kind + "]"
}

class Gauge(title: String, val unit: String) : Panel(title) {
    override val kind: String = "gauge"
    override fun summary(): String =
        title + " [" + kind + ", " + unit + "]"
}

fun main() {
    val g = Gauge(title = "pressure", unit = "bar")
    println("live view: " + g.summary())
}

Output:

registering panel: pressure [null, null]
live view: pressure [gauge, bar]

The intent reads cleanly: construct a Gauge, have the base register it, then query its summary for the live view. The second line is exactly what you would expect -- kind is "gauge", unit is "bar", so the live view prints "pressure [gauge, bar]". The title property, set in the base primary constructor, is populated correctly throughout because it is assigned before anything else runs.

The first line is the alarm. When Gauge(...) runs, the base Panel constructor executes first, and its init block calls summary(). Because summary is open and the object being built is a Gauge, virtual dispatch selects Gauge.summary -- but that override reads kind and unit, and neither has been assigned yet. Subclass property initializers run only after the base constructor returns, so both backing fields still hold their default null. The registry logs "pressure [null, null]", a line that will mislead anyone reading the startup log.

This code compiles and runs, and for the title field it behaves correctly, so the bug hides until someone inspects that first log line. The genuine design flaw is calling an open member (summary, which transitively reads the open property kind) from the base init block: it leaks a reference to a partially constructed object and dispatches into a subclass whose state does not exist yet. The result is not a crash but silent nulls in declared non-null properties -- one of Kotlin's sharpest edges. The fix is to never invoke overridable members during construction: make summary and kind final, or move the registration call to an explicit register() method the caller runs after the object is fully built. As written, the registry is honest about the finished object and lies about the one it is still assembling.

Common Mistakes

  1. Forgetting that classes are final by default. Coming from Java, developers write class Base and then try to subclass it, hitting "This type is final." A class must be explicitly open (or abstract/sealed) before anything can extend it.
  1. Marking a member open on a final class. open fun inside a class that is not itself open or abstract is a contradiction the compiler rejects -- an overridable member on a class no one can subclass has no meaning.
  1. Omitting the override keyword. Kotlin requires override on any member that replaces a base member; leaving it off is a compile error, and adding it to a member the base did not declare open is also an error. The keyword is not optional documentation.
  1. Calling an open member from a constructor or init block. The base constructor runs before subclass initializers, so an overridden method dispatched during construction sees uninitialized state -- null in non-null properties. Never invoke overridable members while an object is still being built.
  1. Confusing abstract with open. An open member has a usable default body; an abstract member has none and forces every concrete subclass to supply one. Marking something abstract when a sensible default exists needlessly pushes work onto subclasses.
  1. Trying to instantiate an abstract class. Fastener() will not compile when Fastener is abstract. Abstract classes exist to be extended; only their concrete subclasses can be constructed.
  1. Assuming the declared type selects the method. With val x: Base = Derived(), calling x.method() dispatches on the runtime type Derived, not the declared type Base. Overridable calls are always virtual.
  1. Overriding a val property with changing state in mind. An overriding property is still resolved virtually, but a val has no setter; if a subclass needs mutable state it must declare a var (and the base member must permit it). Mixing val/var across an override has strict rules the compiler enforces.
  1. Leaving a hierarchy fully open "just in case." Every open member is a promise that subclasses may replace it, constraining how you can change the base later. Seal what should not vary with final (including final override) so the extension surface stays intentional.

Best Practices

  • Keep classes final by default and open only the specific members you have designed for extension, so inheritance is a deliberate contract rather than an accident.
  • Prefer composition over inheritance when a subclass would only reuse code rather than model a genuine "is-a" relationship.
  • Never call open members from constructors or init blocks; do post-construction work in an explicit method the caller invokes on a fully built object.
  • Use abstract for members that have no sensible default and open for those that do, so subclasses are obligated only where a decision genuinely belongs to them.
  • Reach for final override to lock a behaviour partway down a hierarchy while leaving sibling members open.
  • Call super.member() from an override when you mean to extend the base behaviour, and omit it when you mean to replace it -- make the choice explicit.
  • Keep base classes small and their invariants documented, because every open member widens the surface that subclasses can break.
  • Favour sealed hierarchies when the set of subclasses is known and closed, so the compiler can check exhaustiveness at every when.

Practice Exercises

  1. Define an open class Vehicle(val wheels: Int) with an open fun describe(), then a Motorcycle subclass that overrides describe and calls super.describe(). Construct one of each through a Vehicle-typed variable and confirm virtual dispatch picks the right method.
  1. Write an abstract class Shape with an abstract fun area(): Double and a concrete fun report() that uses it. Implement Circle and Rectangle, and verify that Shape() itself does not compile.
  1. Reproduce the leaking-constructor flaw: build a base whose init block calls an open method that reads an open property, and a subclass that overrides both. Observe the null in the construction log, then fix it by making the members final and confirm the log is correct.
  1. Take a three-level hierarchy A -> B -> C where B marks its override final. Confirm that C cannot override that member, then remove final and show that it now can.