Kotlin Inheritance

In this tutorial, we will learn about Inheritance in Kotlin with the help of examples.

Inheritance

Inheritance is one of the key feature of OOP (Object Oriented Programming)Inheritance can be defined as the process where one class is allowed to inherit the features (properties and functions) of another class.

The class which inherits the features of other class is known as sub class (or a derived class or a child class).

The class whose features are inherited is known as super class ( or a base class or  a parent class).

Inheritance supports the concept of reusability, i.e. the code that is present in the parent class doesn’t need to be written again in the child class.

The subclass inherits all members that exist in its superclass (both those that are directly defined in the superclass and the ones that the superclass itself has inherited) and can add some members of their own.

Syntax of Inheritance
open class Superclass {
    //properties and functions  
}

class Subclass : Superclass()
{
    //properties and functions
}

In Kotlin,

  • All classes are final  by default (final class cannot be subclassed) . To inherit, super class for sub class we should use open keyword in front of super class.
  • The sub class inherits a super class using : operator in the class header (after the sub class name or constructor).

When we inherit a class then all the properties and functions are also inherited. We can use the super class properties and functions in the sub class and can also call functions using the sub class object.

Inheritance Example
//Calculator is a super class
open class Calculator {
    var num = 9

    //Calculator class members
    fun add(x: Int, y: Int): Int {
        return x + y
    }

    fun sub(x: Int, y: Int): Int {
        return x - y
    }
}

//sub class CalcAdv inherit Calculator
class CalcAdv : Calculator() {

    //CalcAdv class members
    fun sqr(): Int {
        return num * num   //inherit num property
    }

    fun sqrt(): Double {
        return Math.sqrt(num.toDouble())   //inherit num property
    }
}

fun main(args: Array<String>) {

    //creating CalcAdv instance
    val calcAdv = CalcAdv()

    // calling add() and sub(), which are inherited from Calculator
    println("The sum of the given numbers: " + calcAdv.add(10, 20))
    println("The difference between the given numbers: " + calcAdv.sub(30, 20))


    // calling sqr() and sqrt(), which are CalcAdv's own functions
    println("The square of a given number: " + calcAdv.sqr())
    println("The square root of a given number: " + calcAdv.sqrt())
}
Output
The sum of the given numbers: 30
The difference between the given numbers: 10
The square of a given number: 81
The square root of a given number: 3.0
Example explained

In the above example,

  • We have inherited a subclass CalcAdv from super class Calculator.
  • The CalcAdv class inherits the property num and the functions add() and sub() from the Calculator class.
  • When an object of CalcAdv class is created, a copy of all functions and properties of the super class acquire memory in this object. That is why by using the object of the subclass we can also access the members of a super class.

 

Overriding member functions and properties

Just like Kotlin classes, members (properties and functions) of a Kotlin class are also final by default. To allow a member function to be overridden (redefine or modify the method of its superclass into subclass), you need to mark it with the open modifier.

Moreover, the sub class that overrides a super class function must use the override modifier.

Kotlin program of overriding the member function:
//Employee is a super class
open class Employee {

    open fun show(name: String, age: Int) {
        println("My name is $name, $age years old ")
    }
}

//sub class Manager inherit Employee
class Manager : Employee() {

   //overriding show() to provide new implementation
    override fun show(name: String, age: Int) {
        println("My name is $name ")
        println("I am Manager in HCL company")
    }
}

fun main(args: Array<String>) {
  //creating Manager instance
    val manager = Manager()
  //show() of Manager class will call
    manager.show("Arun", 25)

}
Output
My name is Arun 
I am Manager in HCL company

Similarly, we can override the property of super class in sub class.

Kotlin program of overriding the member property :
//Employee is a super class
open class Employee {
    open var position: String = "Worker"
    open var salary = "20000"

}

// sub class Manager inherit Employee
class Manager : Employee() {
//overriding properties to set new values
    override var position: String = "Manager"
    override var salary = "70000"
}

fun main(args: Array<String>) {
//creating Manager instance
    val m = Manager()
    println("I am " + m.position + " and earning " + m.salary + " per month.")
}
Output
I am Manager and earning 70000 per month.

 

Calling properties and functions of superclass 

When you override a property or a member function of a super class, the super class implementation is shadowed by the child class implementation.

You can access super class member functions or properties from the sub class using the super keyword.

In the below program we have called the super class property color and function draw() in sub class using the super keyword.

Example
//Shape is  a super class
open class Shape {

    val color: String = "blue"

    open fun draw() {
        println("Drawing a shape..")
    }

}

//sub class Rectangle inherit Shape 
class Rectangle : Shape() {

    override fun draw() {
       //calling Shape class draw() and 
       //color property using super keyword
        super.draw()
        println("Filling the rectangle with " + super.color + " color")
    }

}

fun main(args: Array<String>) {
    //creating Rectangle instance
    val rectangle = Rectangle()
    //calling Rectangle class draw()
    rectangle.draw()
}
Output
Drawing a shape..
Filling the rectangle with blue color

 

Leave a Reply