Twitter LogoFacebook Logo
Object Inheritance
Learn about inheritance in Kotlin
By: King

Inheritance is the concept of expanding a class using another class. By doing so, the class that is being expanded will inherit all the properties and functions from the class it used for the expansion.


To declare an inheritance, place the class or type you are trying to inherit after a colon in the class header:

Syntax

class OriginalClass() : [inherit_class] () { }

Example

open class Ball {
    fun roll(){
        
    }
}

class SoccerBall () : Ball() {
    
}

In the example, the SoccerBall class inherited from the Ball class. 


When we create a SoccerBall object, it will also contain the roll() function since it was inherited from the Ball class. 

var soccerBall = SoccerBall()

soccerBall.roll()

The open Keyword

By default, Kotlin classes are final so they cannot be inherited. To make a class inheritable, declare it with the open keyword:

open class Ball {
    ...
}

Overriding

The term override means to overwrite the logic of an existing function that existed in the class it inherited.


In the example, the Ball class has a function call roll() that does nothing. In the SoccerBall class, we can override the roll() function to do something.

In order for the function to be overridable, (1) we need to start the function declaration with the open keyword from the parent class. (2) Then in the child class, we need start the function declaration with the override keyword.

open class Ball {
    open fun roll(){
        
    }
}

class SoccerBall () : Ball() {
    override fun roll() {
        println("Soccer ball is rolling...")
    }
}

It is the same for properties - variables.

open class Ball {
    open val radius = 10;
}

class SoccerBall () : Ball() {
    override val radius = 10;
}

Super Class

The term Super Class refers to the parent class that the class inherited. For the SoccerBall class, the super class is the Ball class.

We can access the properties and function from the super class by using the super keyword.

super.roll()

One of the reason you may want to do this is to expand the current definition of a function.


We will use these class definition for the following example:

open class Ball {
    open fun roll(){
        println("Set the ball")
    }
}

class SoccerBall () : Ball() {
    override fun roll() {
        println("Soccer ball is rolling...")
    }
}

In the example, the SoccerBall class overridden the roll() function so when we create a Soccer Ball object and call the roll() function, it will print "Soccer ball is rolling..."

var soccerBall = SoccerBall()

soccerBall.roll()

What if we want the roll function to also print the original text from the Ball class? We can call the roll() function from the super class in the overridden class to maintain it.

class SoccerBall () : Ball() {

    override fun roll() { 
        super.roll()
        println("Soccer ball is rolling...")
    }

}


Sign In