TExcelTAD
Home › Kotlin › Kotlin Inheritance

Kotlin Inheritance

Inheritance lets one class (the subclass or child) reuse and extend another (the superclass or parent). A Dog is an Animal: it has everything an animal has, plus its own behaviour.

open classes

Kotlin classes are final by default — nobody can inherit from them unless the author explicitly allows it with open. This prevents accidental, fragile inheritance.

kotlin · try it yourself
open class Animal(val name: String) {
    fun eat() = println("$name is eating")
}

class Dog(name: String) : Animal(name) {
    fun fetch() = println("$name fetches the ball")
}

fun main() {
    val rex = Dog("Rex")
    rex.eat()     // inherited
    rex.fetch()   // Dog's own
}
Rex is eating
Rex fetches the ball

The syntax class Dog(name: String) : Animal(name) says "Dog extends Animal, and passes name to Animal's constructor".

Forgetting open gives a clear compile error:

kotlin · try it yourself
class Animal(val name: String)
class Cat(name: String) : Animal(name)

fun main() {
    println(Cat("Tom").name)
}
File.kt:2:27: error: This type is final, so it cannot be extended.

Overriding functions

A subclass can replace a function's behaviour. Both sides must agree: the parent marks the function open, the child marks its version override.

kotlin · try it yourself
open class Animal(val name: String) {
    open fun sound() = "..."
    fun introduce() = println("$name says ${sound()}")
}

class Dog(name: String) : Animal(name) {
    override fun sound() = "Woof"
}

class Cow(name: String) : Animal(name) {
    override fun sound() = "Moo"
}

fun main() {
    val animals = listOf(Dog("Rex"), Cow("Daisy"), Animal("Generic"))
    for (a in animals) a.introduce()
}
Rex says Woof
Daisy says Moo
Generic says ...

This is polymorphism: introduce() is written once in Animal, but sound() calls the right version for the actual object.

Modifier Where Meaning
open class can be inherited from
open member can be overridden
override member overrides a parent member (is itself open unless marked final)
final override member overrides, but stops further overriding

Calling the parent with super

super.member() calls the parent's implementation — useful to extend rather than replace behaviour:

kotlin · try it yourself
open class Employee(val name: String, val salary: Double) {
    open fun describe() = "$name earns $salary"
}

class Manager(name: String, salary: Double, val teamSize: Int) : Employee(name, salary) {
    override fun describe() = super.describe() + " and leads $teamSize people"
}

fun main() {
    println(Employee("Omar", 3200.0).describe())
    println(Manager("Sofia", 5100.0, 6).describe())
}
Omar earns 3200.0
Sofia earns 5100.0 and leads 6 people

Overriding properties

Properties can be open and overridden too:

kotlin · try it yourself
open class Shape {
    open val corners = 0
    fun info() = "${this::class.simpleName} has $corners corners"
}

class Triangle : Shape() { override val corners = 3 }
class Square : Shape() { override val corners = 4 }

fun main() {
    println(Triangle().info())
    println(Square().info())
}
Triangle has 3 corners
Square has 4 corners

Type checks and casts

A variable of the parent type may hold any subclass. Use is to check, and the compiler smart-casts. as casts explicitly (and throws if wrong); as? returns null instead of throwing.

kotlin
val a: Animal = Dog("Rex")
if (a is Dog) a.fetch()          // smart cast
val d = a as? Cow                // null - a is not a Cow

Note: Every Kotlin class implicitly inherits from Any, which provides equals(), hashCode() and toString(). A class can extend only one class but implement many interfaces (next chapter).

Test yourself

Why can't you inherit from a normal Kotlin class by default?

  1. Kotlin has no inheritance
  2. Classes are final unless marked open
  3. You need the extends keyword
  4. Only interfaces can be inherited

How does a subclass call the parent's version of an overridden function?

  1. parent.f()
  2. super.f()
  3. this.f()
  4. base.f()

What does x as? Dog return when x is not a Dog?

  1. It throws ClassCastException
  2. null
  3. An empty Dog
  4. false