Thuta Learning
Kotlin
IntermediateProgrammingBeginner

Inheritance

KotlinLesson 1630 min

What you'll walk away with

  • Explain why Kotlin classes and members are final by default and how open changes that
  • Override functions with override, call the parent version with super and pass arguments to a parent constructor
  • Design an abstract class with abstract and open members and use it polymorphically
  • Avoid the trap of calling an open function from a constructor or init block

Explain it simply

Explain it simply

Inheritance lets one class start from another class's properties and functions instead of rewriting them. Think of a family recipe: a child may follow the parent's recipe, add a pinch of something, or replace one step completely. In code, Dog inherits from Animal, so a Dog can do everything an Animal can do, and it may change how some of it is done.

Kotlin is deliberately cautious here. A class cannot be extended unless its author wrote open, and a member cannot be overridden unless it is open too. Inheriting from someone's class is a promise to keep working when they change it, so the author must opt in.

Problem → Why → Solution

The problem: string tags and scattered when branches

Suppose a pet app stores the kind of animal as a string and writes every behaviour as a when over that string. Adding a hamster means finding every when in the code base and adding a branch, and if you miss one the hamster quietly falls into else. The behaviour of an animal is scattered across functions instead of living with the animal.

string-tags.kt
fun sound(kind: String): String = when (kind) {
    "dog" -> "Woof"
    "cat" -> "Meow"
    else -> "..."
}

fun describe(kind: String): String = when (kind) {
    "dog" -> "a loyal dog"
    "cat" -> "an independent cat"
    else -> "an animal"
}

fun main() {
    println(sound("hamster"))   // "..." because nobody remembered the new kind
}

Why is a string tag a poor design?

A string tag invites typos and forgotten branches, because the compiler cannot tell you which kinds exist. Inheritance moves the choice into the object itself: each class carries its own sound(), and animal.makeSound() picks the right version at runtime, which is polymorphism. Adding a hamster means adding one class, and the code that calls makeSound() stays unchanged.

Core concept: open, override and super

To inherit you need two keywords. The parent writes open class Animal, and every member that children may replace is also open, as in open fun makeSound(). The child names its parent after a colon and calls the parent's constructor: class Dog : Animal(). Without open you get a compile error: "this type is final, so it cannot be extended" for the class, or "'makeSound' in 'Animal' is final and cannot be overridden" for the function.

Overriding is explicit on both sides. The child must write override, and omitting it is an error: "'makeSound' hides member of supertype 'Animal' and needs an 'override' modifier". An overriding member stays open for further subclasses unless you write final override. Inside it, super.makeSound() runs the parent's version, which is how a child extends behaviour instead of replacing it.

If the parent has constructor parameters, the child must pass them on: class Dog(name: String) : Animal(name). An abstract class goes one step further: it can declare abstract members with no body, it cannot be instantiated itself ("cannot create an instance of an abstract class"), and it forces every concrete child to supply them. Abstract members are implicitly open, so you do not write open next to abstract.

The payoff is polymorphism. A variable of type Animal can hold a Dog or a Cat, and animal.makeSound() runs the version belonging to the real object, chosen at runtime. You can test the real type with is, and Kotlin smart-casts inside the branch. Keep hierarchies shallow: the more levels there are, the harder it is to see which version runs, and inheritance fits best for a true is-a relationship.

ModifierMeaningChild's duty
openMay be inherited or overriddenMay override
abstractNo body, class cannot be instantiatedMust override
overrideReplaces a parent memberStays open unless final
final (default)Cannot be extended or overriddenNothing
Mental model: a chain of overrides
  1. Variable type is the parent (Animal)
  2. Real object is the child (Dog)
  3. The call runs the child's override
  4. super.x() can reach the parent's version

The real object's class, not the variable's declared type, decides which function runs.

General pattern

kotlin
open class Parent(val param: Type) {
    open fun action() { /* default behaviour */ }
    fun fixed() { /* cannot be overridden */ }
}

class Child(param: Type) : Parent(param) {
    override fun action() {
        super.action()     // optional: run the parent version too
        // extra behaviour
    }
}

The parent marks the class and the functions it allows to be replaced as open; a non-open function such as fixed() cannot be overridden. The child calls the parent constructor after the colon, as in Parent(param), and may call super.action() inside its override whenever it wants.

Example: Dog replaces Animal's sound

Animal supplies a default sound and Dog replaces it. Because Dog never calls super.makeSound(), Animal's "Animal sound" is never printed, and main sees a single Woof!. Then add a super.makeSound() line inside Dog and predict how the output changes before you run it.

kotlin
open class Animal {
    open fun makeSound() {
        println("Animal sound")
    }
}

class Dog : Animal() {
    override fun makeSound() {
        println("Woof!")
    }
}

fun main() {
    val dog = Dog()
    dog.makeSound()
}

Code breakdown

  1. Open the parent classopen class Animal {

    open lets other classes extend Animal. Without it the class is final and Dog : Animal() fails with "this type is final, so it cannot be extended".

  2. Open the memberopen fun makeSound() {

    Opening the class is not enough; each function that children may replace must be opened one by one. That gives the parent control over which parts can change.

  3. Name the parentclass Dog : Animal() {

    After the colon, Animal() names the parent and calls its constructor. Animal has no parameters, so the parentheses are empty; if it had some, you would pass arguments here.

  4. Overrideoverride fun makeSound() {

    override declares that this function replaces the parent's makeSound. Name, parameters and return type must match the parent, and leaving override out is an error.

  5. Replace the behaviourprintln("Woof!")

    Dog's body replaces the parent's body, so "Animal sound" is not printed. To keep the parent's work too, call super.makeSound() before this line.

  6. Call itdog.makeSound()

    At runtime the real class of dog is Dog, so Dog's version runs. Declaring the variable as val dog: Animal = Dog() would still print Woof!.

You should see
Woof!
What happens on dog.makeSound()
  1. dog.makeSound() is called
  2. Look up the real class: Dog
  3. Does Dog override makeSound()?

Yes, it overrides

Dog's version runs and prints Woof!

No override

the inherited Animal version runs

Overriding, super and polymorphism

In this snippet Cat calls super.makeSound() to add to the parent's work, while Dog replaces it entirely. The List<Animal> mixes a Dog, a Cat and a plain Animal, yet calling p.makeSound() on each runs that object's own version. is checks the real class, and inside if (a is Dog) Kotlin smart-casts a to Dog so you need no explicit cast.

polymorphism.kt
open class Animal {
    open fun makeSound() {
        println("Animal sound")
    }
}

class Dog : Animal() {
    override fun makeSound() {
        println("Woof!")
    }
}

class Cat : Animal() {
    override fun makeSound() {
        super.makeSound()
        println("Meow")
    }
}

fun main() {
    val dog = Dog()
    dog.makeSound()
    val pets: List<Animal> = listOf(Dog(), Cat(), Animal())
    for (p in pets) p.makeSound()
    val a: Animal = Dog()
    println(a is Dog)
    println(a is Cat)
    if (a is Dog) println("smart cast ok")
}

Abstract classes and passing constructor arguments

Employee is abstract and declares bonus() with no body, so every Engineer and Manager must supply it. pay() is open, so Manager calls super.pay() and adds 1000. describe() is not open, so children cannot change it: it is a promise that the text always combines title(), name and pay(). Notice too how each child passes its arguments up with Employee(name, baseSalary). protected means visible to the class and its subclasses only.

employees.kt
abstract class Employee(val name: String, protected val baseSalary: Int) {
    abstract fun bonus(): Int
    open fun pay(): Int = baseSalary + bonus()
    open fun title(): String = "Employee"
    fun describe(): String = "${title()} $name earns ${pay()}"
}

class Engineer(name: String, baseSalary: Int) : Employee(name, baseSalary) {
    override fun bonus(): Int = 500
    override fun title(): String = "Engineer"
}

class Manager(
    name: String,
    baseSalary: Int,
    private val reports: Int,
) : Employee(name, baseSalary) {
    override fun bonus(): Int = reports * 200
    override fun pay(): Int = super.pay() + 1000
    override fun title(): String = "Manager"
}

fun main() {
    val staff: List<Employee> = listOf(Engineer("Aye", 3000), Manager("Kyaw", 4000, 3))
    for (e in staff) println(e.describe())
    println(staff.sumOf { it.pay() })
}

The trap: calling an open function from a constructor

When an object is built, the parent's init block runs before the child's property initializers. If the parent's init calls an open function, the child's override runs, but the child's properties have not been initialised yet. Below, Child.label() reads name, yet when Base's init calls it, name is still null even though it is declared as a String. It compiles and does not crash, which makes it dangerous: the wrong value spreads quietly.

open-in-init.kt
open class Base {
    init {
        println("Base init sees: " + label())
    }

    open fun label(): String = "base"
}

class Child : Base() {
    private val name = "child"

    override fun label(): String = "I am " + name
}

fun main() {
    Child()                        // prints "I am null": name is not set yet
    println(Child().label())       // by now the object is complete
}

In real projects

Where this shows up in real projects

Frameworks lean on inheritance heavily. On Android you write class MainActivity : AppCompatActivity(), override onCreate and must call super.onCreate(...). Your own exceptions look like class ValidationException(message: String) : Exception(message). UI toolkits keep the shared behaviour of every screen in one abstract base class, and each screen overrides only the parts it needs.

Because classes are final by default, frameworks such as Spring that need to proxy your classes require them to be open, and the kotlin-spring compiler plugin opens classes carrying Spring annotations for you. In your own business code, use inheritance for a genuine is-a relationship, and when you only want to reuse behaviour prefer composition, meaning an object held as a property, and interfaces. That reduces how often a change in a parent breaks its subclasses.

Common mistakes

Common mistakes

1. Forgetting to open the parent

With class Animal and class Dog : Animal() you get "this type is final, so it cannot be extended". An unopened function fails with "'makeSound' in 'Animal' is final and cannot be overridden". If the parent is yours, open the class and the function; if it belongs to someone else, think about composition.

2. Forgetting override

With open fun makeSound() in the parent and a plain fun makeSound() in the child, the compiler reports "'makeSound' hides member of supertype 'Animal' and needs an 'override' modifier". Kotlin is strict here to stop accidental name clashes.

3. Not passing arguments to the parent constructor

With open class Animal(val name: String), writing class Dog : Animal() fails with "no value passed for parameter 'name'". Write class Dog(name: String) : Animal(name) and pass the value up.

4. Calling an open function from a constructor

When a parent's init calls an open function, the child's override runs before the child's properties are initialised and reads null or 0, as the deeper section above shows. Do not call open members from a constructor or init block.

Best practices

Best practices

  • Do not inherit just to reuse behaviour: inherit for a true is-a relationship and solve the rest with composition and interfaces.
  • Keep the open surface small, document how children should override, and close it with final override when the design settles.
  • Keep hierarchies two or three levels deep, and never call open members from a constructor or init block.

Mini challenge

Mini challenge: a Shape hierarchy

Build an abstract Shape class with three concrete shapes, sort them by area and print their descriptions.

  • abstract class Shape(val name: String) has abstract fun area(): Double and an open describe() that uses name and area()
  • Rectangle(w, h) and Triangle(base, height) override area()
  • Square(side) overrides area() and extends describe() by calling super.describe()
  • main sorts the shapes by area, prints each description, then prints the name of the biggest shape
shapes.kt
abstract class Shape(val name: String) {
    // TODO: abstract fun area(): Double
    // TODO: open fun describe(): String   ("<name> with area <area>")
}

// TODO: class Rectangle(w: Double, h: Double) : Shape("Rectangle")
// TODO: class Triangle(base: Double, height: Double) : Shape("Triangle")
// TODO: class Square(side: Double) : Shape("Square") that extends describe() with super

fun main() {
    // TODO: listOf(Rectangle(4.0, 3.0), Triangle(5.0, 5.0), Square(2.0))
    // TODO: print every description, smallest area first
    // TODO: print the name of the shape with the largest area
}

Expected: The program prints these four lines: Square with area 4.0 (all sides 2.0) Rectangle with area 12.0 Triangle with area 12.5 Triangle

Show hint

Sort with shapes.sortedBy { it.area() } and find the biggest with shapes.maxByOrNull { it.area() }?.name. Write Square's describe() as super.describe() + " (all sides " + side + ")". Doubles print in the form 4.0.

Show solution
shapes.kt
abstract class Shape(val name: String) {
    abstract fun area(): Double

    open fun describe(): String = "$name with area ${area()}"
}

class Rectangle(private val w: Double, private val h: Double) : Shape("Rectangle") {
    override fun area(): Double = w * h
}

class Triangle(private val base: Double, private val height: Double) : Shape("Triangle") {
    override fun area(): Double = base * height / 2
}

class Square(private val side: Double) : Shape("Square") {
    override fun area(): Double = side * side

    override fun describe(): String = super.describe() + " (all sides " + side + ")"
}

fun main() {
    val shapes = listOf(Rectangle(4.0, 3.0), Triangle(5.0, 5.0), Square(2.0))
    for (s in shapes.sortedBy { it.area() }) println(s.describe())
    println(shapes.maxByOrNull { it.area() }?.name)
}

Quick quiz 1 / 3

If Animal is declared without open and you write class Dog : Animal(), what does the compiler say?

Quick quiz 2 / 3

With open class A { init { println(describe()) }; open fun describe() = "A" } and class B : A() { private val tag = "B"; override fun describe() = "tag=" + tag }, what does B() print?

Quick quiz 3 / 3

Which statement about an abstract member is true?

What to remember

  • Kotlin classes and members are final by default; the parent opts in with open, and the child replaces a member with the override keyword.
  • The child calls the parent constructor with arguments after the colon and can still reach the parent version with super.member().
  • An abstract class has bodiless members, cannot be instantiated and forces every concrete child to fill them in; polymorphism runs the real object's version, not the variable type's.
  • Never call an open function from a constructor or init block: the child's properties are not initialised yet and read as null.

Kotlin language guide — Kotlin

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Inheritance | Thuta Learning