Kotlin Programming – Classes and Inheritance

In this tutorial you’ll learn about classes and inheritance in Kotlin. To follow along, you can make use of the Kotlin – Playground.

Classes and Inheritance

When you define a class, you can decide whether you will allow other classes to inherit from that class. A class which inherits from another, is known as a subclass. A class which allows inheritance, is known as a superclass. Inheritance allows a subclass to inherit its superclass‘ properties, methods and other characteristics.

Defining a Base Class

A class is final by default in Kotlin. If we want a class to accept inheritance, we have to define it with the keyword open followed by the keyword class. Similarly, if we want our functions in our base class to accept inheritance, we have to define it with the keyword open followed by the keyword fun. The same is true for properties as well. Let’s try an example of a base class in action.

open class Smartphone {
    var sendSms = true
    var accessInternet = true
    var exchangeEmail = true
    var longBatteryLife = true
    open var isWaterproof = false
    
    fun getDescription() = "${if (sendSms) "can" else "cannot"} send sms, ${if (accessInternet) "has" else "has no"} access to the internet, ${if (exchangeEmail) "can" else "cannot"} exchange email and ${if (longBatteryLife) "has" else "does not have"} a long battery life."
     
    open fun playRingtone() {
        println("plays a default ringtone")
    }
}

fun main() {
    val smartphone = Smartphone()
    println("A smartphone ${smartphone.getDescription()}")
}

Subclassing

Subclassing is defining a new class with the intention of inheriting another class. Let’s see subclassing in action.

class IPhone() : Smartphone() {
    var model = "iPhone 8"
}
 
fun main() {
    val iPhone = IPhone()
    iPhone.model = "iPhone X"
    println("${iPhone.model} ${iPhone.getDescription()}")
}

Overriding

In our base class SmartPhone, we have a method playRingtone(). Let’s say we want to output a different text in the console with our iPhone‘s instance. We can override the method playRingtone() in our subclass to do that.

class IPhone() : Smartphone() {
    override var isWaterproof = true
    var model = "iPhone 8"
     
    override fun playRingtone() {
        println("$model plays the ringtone 'Let Me Love You (Marimba Remix)'.")
    }
}

fun main() {
    iPhone.playRingtone()
}

Reference

https://kotlinlang.org/docs/reference/classes.html

Advertisement