Inheritance in Kotlin

Inheritance is a core concept of Object-Oriented Programming (OOP) that allows a class to acquire properties and behavior (methods) from another class. Kotlin supports single inheritance (a class can inherit from only one class) but allows multiple interface implementations. Inheritance promotes code reuse, extensibility, and polymorphism.

1. Why Inheritance Matters

2. How Inheritance Works in Kotlin

By default, classes in Kotlin are final (cannot be inherited). To allow inheritance, you must mark the class as open. Similarly, functions or properties must be marked open if you want them to be overridden in a subclass.

2.1 Basic Inheritance Example


open class Aircraft(val name: String) {
    open fun fly() {
        println("$name is flying")
    }

    fun status() {
        println("$name is ready for flight")
    }
}

class Jet(name: String, val maxSpeed: Int) : Aircraft(name) {
    override fun fly() {
        println("$name flies at max speed of $maxSpeed km/h")
    }
}

fun main() {
    val plane: Aircraft = Jet("Falcon", 1200)
    plane.status()   // Calls parent class function
    plane.fly()      // Calls overridden function in subclass
}
  

Output:


Falcon is ready for flight
Falcon flies at max speed of 1200 km/h
  

2.2 Notes on Inheritance

3. Inheritance and Constructors

When inheriting a class, the parent’s constructor must be called. Kotlin supports calling the primary constructor of the parent directly in the subclass declaration.


open class Aircraft(val name: String, val capacity: Int)

class CargoPlane(name: String, capacity: Int, val cargoWeight: Int) : Aircraft(name, capacity)

fun main() {
    val cargo = CargoPlane("Hercules", 50, 2000)
    println("${cargo.name} carries ${cargo.cargoWeight} tons")
}
  

4. Inheriting Interfaces

Kotlin allows multiple interface implementations even though class inheritance is single. This is useful for adding behavior from multiple sources.


interface Flyable {
    fun fly()
}

interface Movable {
    fun move()
}

class Drone : Flyable, Movable {
    override fun fly() {
        println("Drone is flying")
    }

    override fun move() {
        println("Drone is moving")
    }
}
  

5. Technical Interview Questions

6. Key Takeaways