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.
| Modifier | Applies to | Can be instantiated? | Can be subclassed / overridden? |
|---|---|---|---|
final (default) | class or member | class: yes | no |
open | class or member | class: yes | yes |
abstract | class or member | class: no | must be |
sealed | class | no | only in same module/file |
final override | overriding member | n/a | stops 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
- Forgetting that classes are final by default. Coming from Java, developers write
class Baseand then try to subclass it, hitting "This type is final." A class must be explicitlyopen(orabstract/sealed) before anything can extend it.
- Marking a member
openon a final class.open funinside a class that is not itselfopenorabstractis a contradiction the compiler rejects -- an overridable member on a class no one can subclass has no meaning.
- Omitting the
overridekeyword. Kotlin requiresoverrideon any member that replaces a base member; leaving it off is a compile error, and adding it to a member the base did not declareopenis also an error. The keyword is not optional documentation.
- Calling an
openmember from a constructor orinitblock. The base constructor runs before subclass initializers, so an overridden method dispatched during construction sees uninitialized state --nullin non-null properties. Never invoke overridable members while an object is still being built.
- Confusing
abstractwithopen. Anopenmember has a usable default body; anabstractmember has none and forces every concrete subclass to supply one. Marking somethingabstractwhen a sensible default exists needlessly pushes work onto subclasses.
- Trying to instantiate an abstract class.
Fastener()will not compile whenFasteneris abstract. Abstract classes exist to be extended; only their concrete subclasses can be constructed.
- Assuming the declared type selects the method. With
val x: Base = Derived(), callingx.method()dispatches on the runtime typeDerived, not the declared typeBase. Overridable calls are always virtual.
- Overriding a
valproperty with changing state in mind. An overriding property is still resolved virtually, but avalhas no setter; if a subclass needs mutable state it must declare avar(and the base member must permit it). Mixingval/varacross an override has strict rules the compiler enforces.
- 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 withfinal(includingfinal override) so the extension surface stays intentional.
Best Practices
- Keep classes
finalby 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
openmembers from constructors orinitblocks; do post-construction work in an explicit method the caller invokes on a fully built object. - Use
abstractfor members that have no sensible default andopenfor those that do, so subclasses are obligated only where a decision genuinely belongs to them. - Reach for
final overrideto 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
openmember widens the surface that subclasses can break. - Favour
sealedhierarchies when the set of subclasses is known and closed, so the compiler can check exhaustiveness at everywhen.
Practice Exercises
- Define an
open class Vehicle(val wheels: Int)with anopen fun describe(), then aMotorcyclesubclass that overridesdescribeand callssuper.describe(). Construct one of each through aVehicle-typed variable and confirm virtual dispatch picks the right method.
- Write an
abstract class Shapewith an abstractfun area(): Doubleand a concretefun report()that uses it. ImplementCircleandRectangle, and verify thatShape()itself does not compile.
- Reproduce the leaking-constructor flaw: build a base whose
initblock calls anopenmethod that reads anopenproperty, and a subclass that overrides both. Observe thenullin the construction log, then fix it by making the membersfinaland confirm the log is correct.
- Take a three-level hierarchy
A->B->CwhereBmarks its overridefinal. Confirm thatCcannot override that member, then removefinaland show that it now can.