SyntaxStudy
Sign Up
Kotlin Inheritance and Interfaces
Kotlin Beginner 1 min read

Inheritance and Interfaces

Kotlin classes are final by default — you must mark a class open before it can be subclassed. This design decision prevents accidental inheritance and makes APIs more predictable. Similarly, properties and functions that should be overridable must be marked open. Interfaces in Kotlin are similar to Java 8+ interfaces: they can declare abstract members, provide default implementations, and even store state through abstract properties. A class may implement multiple interfaces, while it can extend at most one superclass. When a class inherits from an open class and also implements an interface that both provide the same method, the override keyword is mandatory, and you use super.methodName() to disambiguate which parent implementation to call.
Example
interface Drawable {
    val color: String          // abstract property
    fun draw()                  // abstract method
    fun describe() = "I am a ${color} drawable"   // default impl
}

interface Resizable {
    fun resize(factor: Double)
}

// open allows subclassing
open class Shape(override val color: String) : Drawable {
    override fun draw() = println("Drawing a $color shape")
}

// Inherits Shape, implements Resizable
class Circle(color: String, var radius: Double)
    : Shape(color), Resizable {

    override fun draw() {
        super.draw()                 // calls Shape.draw()
        println("  (circle r=$radius)")
    }

    override fun resize(factor: Double) {
        radius *= factor
    }
}

// Abstract class — cannot be instantiated directly
abstract class Vehicle(val brand: String) {
    abstract fun fuelType(): String
    fun info() = "$brand runs on ${fuelType()}"
}

class ElectricCar(brand: String) : Vehicle(brand) {
    override fun fuelType() = "electricity"
}

fun main() {
    val c = Circle("red", 5.0)
    c.draw()
    println(c.describe())
    c.resize(2.0)
    println("New radius: ${c.radius}")

    val car = ElectricCar("Tesla")
    println(car.info())
}