Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 09 / Topic 2 of 10

Inheritance: open, override, super

Every class in Kotlin is final unless you mark it open — the opposite default from Java. A member inside a class is also final unless marked open, and even then a subclass must write override explicitly; there's no accidentally shadowing a parent's method by giving yours the same signature.

open class Employee(val name: String, protected val baseSalaryInr: Double) {
    open fun payslip(): String = "$name: base ₹%.2f".format(baseSalaryInr)

    // Not marked `open` -- subclasses cannot override this one.
    fun employeeId(): String = name.take(3).uppercase() + baseSalaryInr.toInt()
}

class Manager(name: String, baseSalaryInr: Double, private val teamSize: Int) :
    Employee(name, baseSalaryInr) {

    private val leadershipAllowance = teamSize * 500.0

    override fun payslip(): String =
        super.payslip() + " + leadership allowance ₹%.2f (team of %d)".format(leadershipAllowance, teamSize)
}

super.payslip() calls the parent's version and builds on it, instead of duplicating its formatting. Running this against a mixed list of Employee, Manager and Intern:

val staff: List<Employee> = listOf(
    Employee("Kavita Rao", 55000.0),
    Manager("Arjun Mehta", 75000.0, teamSize = 4),
    Intern("Divya Shah", 12000.0)
)
for (person in staff) println(person.payslip())
println("Runtime types: ${staff.map { it::class.simpleName }}")
Kavita Rao: base ₹55000.00
Arjun Mehta: base ₹75000.00 + leadership allowance ₹2000.00 (team of 4)
Divya Shah: stipend ₹12000.00 (no base salary)
Manager's own employeeId(): ARJ75000
Runtime types: [Employee, Manager, Intern]

Each call to payslip() runs a different override depending on the object's actual runtime type — not the Employee type the List was declared with. That's polymorphism: one call site, many possible bodies, picked at runtime by what the object really is.

Full program: examples/01_inheritance.kt.

Done here? The practice set for Part 9 — including the solutions — is on the part page.

Search the guide