Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 134 ยท Classes and Objects

Inheritance

Learn Kotlin inheritance: classes are final by default, open and override, calling super, superclass constructors, overriding properties, polymorphism and the open-member-in-constructor trap.

Inheritance lets one class build on another. A Dog is an Animal: it has everything an animal has and adds or changes some behavior. The subclass reuses the superclass's code, and anywhere an Animal is expected you may pass a Dog. That second part, substitutability, is what makes inheritance powerful and also what makes it dangerous when it is used carelessly.

Kotlin takes a deliberate stance: every class is final by default. To allow subclasses you must say open, and to allow a member to be overridden you must say open on it as well. This lesson shows how that works, how super constructors and super calls behave, how properties are overridden, and why the Kotlin designers prefer composition when you are in doubt.

Classes are final by default

Kotlin Inheriting from a final class (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This does not compile: main.kt:3:27: error: this type is final, so it cannot be extended. Java programmers are used to the opposite default, but Kotlin's rule follows a well-known piece of advice: design for inheritance or prohibit it. A class that was never designed to be extended can break in surprising ways when someone subclasses it. Adding open is a conscious promise that the class is built for it.

open classes and the superclass constructor

Mark the class open, and list the superclass after a colon with a call to its constructor:

Kotlin A first subclass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The loop prints Rex says woof, Tom says meow and Thing says .... Several rules appear in this small example:

  • Animal(name) after the colon is the superclass constructor call. The subclass must pass the arguments the superclass needs. (A class with a primary constructor calls it there; a class with only secondary constructors uses super(...) in each one.)
  • open fun sound() can be overridden; introduce() is not open, so it is final and no subclass can change it.
  • override is mandatory in the subclass. Forgetting it is an error, and so is writing override when there is nothing to override.
  • The static type of pets is List<Animal>, yet each call to sound() runs the version of the object's real class. This is polymorphism.

An overriding member is itself open unless you write final override, which is useful to stop a chain of overrides at a given class.

Overriding rules the compiler enforces

Kotlin Missing open or override (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You get two errors, one for each mistake: error: 'greet' in 'Base' is final and cannot be overridden. for the first and error: 'wave' hides member of supertype 'Base' and needs an 'override' modifier. for the second. These messages are a feature: Kotlin never lets a subclass silently replace or shadow a superclass member.

Calling the superclass with super

Inside an override, super.member() calls the implementation you replaced. That lets you extend behavior instead of rewriting it:

Kotlin Extending behavior with super

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is [log] 12:00 started followed by [log] STARTED!. The fixed clock string keeps the output predictable; in real code you would read the time.

Overriding properties

Properties can be open and overridden just like functions. An override may turn a val into a var but never the other way round, and it may supply a different initial value or even a custom getter:

Kotlin Overriding properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The three lines are 4: vehicle with 4 wheels, 2: vehicle with 2 wheels and 3: tricycle!. Properties can also be declared directly in the constructor with override val: class Motorbike(override val wheels: Int) : Vehicle().

The trap: open members called from constructors

Here is the most famous inheritance bug. A superclass constructor runs before the subclass's own properties are initialized. If the constructor (or an init block) calls an open member that the subclass overrides, the override runs on a half-built object:

Kotlin Calling an open member in init (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program crashes with Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because the return value of "Report.getTitle()" is null and a stack trace that points into Report.<init>. The title getter that runs during the base init belongs to SalesReport, but its backing field is not assigned yet, so it returns null even though the type says String. The compiler did not warn here, so this bug is yours to avoid.

The rule: never call open members from a constructor or init block of a class that can be extended. Do the work in a regular method that callers invoke afterwards, or make the member final.

Type checks and casts in hierarchies

Because a Dog is an Animal, you can test and convert. The compiler remembers the check (a smart cast), so no explicit cast is needed afterwards:

Kotlin is, as? and smart casts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The areas are 3.14, 6.00 and 0.00, and the safe cast as? of a circle to Rect yields null. Long when (shape) { is ... } chains are a hint that sealed classes would give you a closed set with an exhaustive check, which is safer than an open hierarchy with an else branch. See also Type Checks and Casts.

Abstract classes in one paragraph

An abstract class cannot be instantiated and may declare abstract members without bodies that subclasses must implement; abstract members are open automatically. Abstract Classes covers when to choose them over interfaces.

Composition over inheritance

Inheritance ties a subclass to the implementation details of its parent: if the parent changes how a method calls its own other methods, subclasses can break. That is the fragile base class problem. A common recommendation is to prefer composition: keep an object as a field and forward to it, instead of inheriting from it.

Kotlin Composition instead of inheritance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Kotlin makes the forwarding part painless with delegation (for example class CountingList(inner: MutableList<String>) : MutableList<String> by inner). Use inheritance when the relationship is truly is-a, the superclass was designed to be extended, and you override only a small, documented set of members. Otherwise compose.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens if you write class Dog : Animal() when Animal is declared as class Animal?

    Kotlin classes are final unless marked open (or abstract, sealed, and so on).
  2. 2. Which keyword must a subclass use when it replaces a superclass member?

    override is mandatory, and the member being overridden must itself be open (or abstract).
  3. 3. What does super.log(message) do inside an override of log?

    super refers to the superclass, so you can reuse its implementation and add behavior around it.
  4. 4. Why can calling an open property from a superclass init block crash?

    The base constructor runs before the subclass's initializers, so the override sees an unassigned field (null or zero).
  5. 5. Which design is a common alternative to deep inheritance hierarchies?

    Composition avoids the fragile base class problem and Kotlin's by delegation reduces the forwarding boilerplate.

Summary

  • Classes and members are final by default; add open to allow subclassing or overriding, and always write override.
  • A subclass calls its superclass constructor in the header: class Dog(name: String) : Animal(name).
  • super.member() runs the superclass version; final override stops further overriding.
  • Properties can be overridden too (a val may become a var, not the reverse).
  • Never call open members from constructors or init blocks: the subclass is not initialized yet.
  • Prefer composition and delegation unless the relationship is truly is-a and the base class was designed for extension.

Next: Interfaces