Inheritance Basics

Classes are Final by Default

Inheritance lets a class (child / subclass) reuse the properties and functions of another class (parent / superclass). In Kotlin every class is final by default - you must mark the parent with open to allow inheritance. This prevents accidental, fragile inheritance.

Animal  (open)
        /     \
     Dog       Cat
   class Dog : Animal()

Extending a Class

Example

The child writes : Parent(...) and passes the parent's constructor arguments.

open class Animal(val name: String) {
    fun eat() = println("$name is eating")
}

class Dog(name: String) : Animal(name) {
    fun bark() = println("$name says Woof")
}

class Cat(name: String) : Animal(name) {
    fun meow() = println("$name says Meow")
}

fun main() {
    val dog = Dog("Bruno")
    dog.eat()      // inherited
    dog.bark()     // own function
    val cat = Cat("Kitty")
    cat.eat()
    cat.meow()
}

Output

Bruno is eating
Bruno says Woof
Kitty is eating
Kitty says Meow

Any: the Root of All Classes

Every Kotlin class inherits from Any, which provides toString(), equals() and hashCode(). That is why you can call toString() on any object.

Note: Without open, class Dog : Animal() fails with "This type is final, so it cannot be inherited from".