liveBook · Manning

Final

As explained in Kotlin in Action, 2E

The final modifier prevents a Kotlin class from being subclassed or a class member from being overridden.

Kotlin uses final by default: classes cannot be subclassed, and their methods and properties cannot be overridden. This protects class behavior from fragile base class changes. Use open explicitly when inheritance or overriding is part of the design. section 4.1.2

Allow one override, forbid another

open class RichButton : Clickable { final override fun click() { /* basic behavior */ } open fun animate() { /* customizable behavior */ } } class ThemedButton : RichButton() { override fun animate() { /* allowed */ } // override fun click() { /* compilation error */ } } The class must be open before it can be subclassed. Each member must also be open before a subclass can override it; final can close an otherwise overridable member. section 4.1.2

Use the modifiers together to make inheritance boundaries explicit:

  • final prevents a class member from being overridden and is the default for Kotlin members. section 4.1.2
  • open permits subclassing or overriding, but must be written on both the class and each customizable member. section 4.1.2
  • override identifies a member that replaces a superclass or interface member; the replacement remains open unless marked final. section 4.1.2
  • Java permits inheritance by default, whereas Kotlin requires deliberate opt-in, reducing unexpected coupling between base classes and subclasses. section 4.1.2
Listing 4.10 Forbidding an override
open class RichButton : Clickable {
    final override fun click() { /* ... */ }   #1
}

Inspect the compact declaration that forbids a subclass from overriding an inherited member. section 4.1.2

How Kotlin in Action, 2E covers it

How deep it goes
Explains default restrictions, explicit open points, final overrides, and the fragile base class problem without descending into compiler internals.
Examples
Uses RichButton and ThemedButton to separate overridable animation behavior from protected button behavior.
What it assumes
Assumes basic Kotlin classes, methods, properties, interfaces, and Java inheritance conventions.
What you can do after
Evaluate/understand how to design Kotlin hierarchies with deliberate subclassing and overriding boundaries.
How it connects
Connects final with open, override, abstract classes, interfaces, and the fragile base class problem.

Also explained in

Compare how 3 books explain final →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.