Kotlin Inheritance

One of the most important aspects of object-oriented programming is inheritance. It enables the user to create a new class from an existing class (base class).

The derived or new class acquires all the features of the base class and may have new options of its own.

Before we dig deeper into the details of Kotlin inheritance, I recommend that you read the following article: Kotlin Classes and Constructors

Any class

All the classes in Kotlin share a common superclass, that is Any, it serves as the default superclass for classes with no declared supertypes:

class Person()  // Implicitly inherits from Any

Any class has three methods defined in it : , hashCode(), equals() and toString(). Thus, these methods are defined for all the Kotlin classes.

How to Inherit a class

In Kotlin, by default, classes are declared as final – they can not be inherited. To make a class inheritable, a class is declare with open keyword as follow :

open class Person//    Class is open for inheritance

To inherit a base/super class, place the type (class name) after a colon in the class header:

open class Person(id: Int)

class Cricketer(id: Int) : Person(id)

If the child (derived) class has a primary constructor, the base class must be initialized in that primary constructor according to its parameters.

If the child (derived) class has no primary constructor, then each secondary constructor has to initialize the base type using the super keyword

open class Person(id: Int)

class Cricketer: Person
{
    constructor(id: Int) : super(id)

    constructor(id: Int, name: String) : super(id)
}

How to Override methods

open class MyShape {
    open fun drawImage() 
    { 
        /*...*/ 
    }
    fun fill() 
    { 
        /*...*/ 
    }
}

class Circle() : MyShape() 
{
    override fun drawImage() 
    { 
        /*...*/ 
    }
}
  • Class : by default class is declared as final, open keyword is required to mark the class as inheritable.
  • Members: by default a member in a class is declared as final, to override them in derived class it must be marked as open.

Method overriding example

// www.raviroza.com
// 03-Feb-2022, 5.38 pm
open class Movie
{
    open fun play()
    {
        println("movie is playing")
    }
}
class Song : Movie()
{
    override fun play()
    {
        super.play()
        println("song is playing")

    }
}

fun main() {
    var s = Song()
    s.play()
}
/*

OUTPUT
movie is playing
song is playing

*/

In above example, Movie is the base class and Song is the derived class. As it is shown here open keyword is required to make a class inheritable. Method play() is also declared as an open, because it is to be overridden by the derived class. Moreover, the play() method of super class is called from the play() method of derived class using super keyword.