Inheritance


What is Inheritance in Kotlin ?

Inheritance in Kotlin is a mechanism in which one object acquires all the properties and behaviors of parent object. The idea behind inheritance in Kotlin is that you can create new classes that are built upon existing classes.

It is possible for classes to inherit or acquire the properties and functions of other classes, just like a son can acquire some traits and behavior from his father.

To Allow other classes in inherit from a class (base Class), then you have to make the base class as Open.

By default you cannot inherit any class in kotlin as every class in kotlin is final.


open class BaseClass{
    
}

In Kotlin, inheritance is declared using the : operator and then you have to mention the Super/base class name.


open class BaseClass{
    fun printSomething(){
        println("I am function in base class")
    }
    var baseValue = 56
}
class DerivedClass : BaseClass(){
    fun baseClassFunction(){
        // calling a base class function
        printSomething()
        // calling a base class variable
        println(baseValue)
    }
}
fun main(args: Array<String>)
{
    var d = DerivedClass()
    // calling derived class method
    d.baseClassFunction()
}

Child Class / Sub Class /Derived Class : The class that extends the features of another class is known as child class, sub class or derived class.

Parent Class / Super class / Base Class : The class whose properties and functionalities are used(inherited) by another class is known as parent class, super class or Base class.

We can also call the methods present in the base class using the derived class objects in kotlin, like below


open class BaseClass{
    fun printSomething(){
        println("I am function in base class")
    }
    var baseValue = 56
}
class DerivedClass : BaseClass(){
    // this class has nothing as of now
}
fun main(args: Array<String>)
{
    var d = DerivedClass()
    // calling a base class function
    d.printSomething()
    // calling a base class variable
    println(d.baseValue)
}

Kotlin Standard Functions

Constructor involvement in Inheritance

If you see the above inheritance programs, we have used the Base class name after the colon :, but if you notice, we have used a constructor.

Do not forget that constructor also has the ( ) after the name of the class. We are initialing it there

You must Initiate the base/super class constructor to access the methods present in the super class.

You can Initiate the base class constructor in two places:

Along with Primary Constructor of Derived class

Base class constructor accepts a parameter, so while initializing the Base class constructor we have to pass an string argument.


open class BaseClass(var name:String){
    fun printSomething(){
        println("The name is $name")
    }
    var baseValue = 56
}
class DerivedClass:BaseClass("chercher tech"){
    fun baseClassFunction(){
        // calling a base class function
        printSomething()
        // calling a base class variable
        println(baseValue)
    }
}
fun main(args: Array<String>)
{
    var d = DerivedClass()
    // calling derived class method
    d.baseClassFunction()
}

Along with Secondary of Derived class using super()

Re-writing the same above example with Secondary constructor


open class BaseClass(var name:String){
    fun printSomething(){
        println("The name is $name")
    }
    var baseValue = 56
}
class DerivedClass:BaseClass{
    constructor():super("chercher tech"){
        // i am secondary constructor
    }
    fun baseClassFunction(){
        // calling a base class function
        printSomething()
        // calling a base class variable
        println(baseValue)
    }
}
fun main(args: Array<String>)
{
    var d = DerivedClass()
    // calling derived class method
    d.baseClassFunction()
}

What if I initialize the base class constructor in both primary and secondary constructors, then you get error. You must have base class initialization code either with primary constructor or with Secondary constructor

Error:(17, 20) Kotlin: Supertype initialization is impossible without primary constructor

open class BaseClass{
    fun printSomething(){
        println("I am function in base class")
    }
    var baseValue = 56
}
class DerivedClass : BaseClass(){
    // this class has nothing as of now
}
fun main(args: Array<String>)
{
    var d = DerivedClass()
    // calling a base class function
    d.printSomething()
    // calling a base class variable
    println(d.baseValue)
}

More Secondary Constructors :

If you have more than one secondary constructor then all the secondary constructor must initialize the base class.


open class BaseClass(var name:String){
    fun printSomething(){
        println("The name is $name")
    }
    var baseValue = 56
}
class DerivedClass:BaseClass{
    // secondary constructor without parameter
    constructor():super("hello"){
    }
    // secondary constructor with parameter
    constructor(author:String):super("chercher tech"){
        println("Author name is $author")
    }
    fun baseClassFunction(){
        // calling a base class function
        printSomething()
        // calling a base class variable
        println(baseValue)
    }
}
fun main(args: Array<String>)
{
    var d = DerivedClass()
    // calling derived class method
    d.baseClassFunction()
    // initializing the param constructor
    var paramCon = DerivedClass("karthiQ")
    paramCon.baseClassFunction()
}

returns in lambdas

this() & super() functions in kotlin

In above code, I have used the super() function what it means, super() function is used to call the super class constructor, to call super class constructor we have to pass the right number of parameters to the super() function.


open class BaseClass(var name:String){
    fun testa(){
        println("testA")
    }
}
class ChildClass:BaseClass{
    constructor():super("karthiq"){
    }
    fun testb(){
        println("testB")
    }
}
fun main(args: Array<String>)
{
    var gc = ChildClass()
    // calling methods from base and child classes
    gc.testa()
    gc.testb()
}

this() function only can be used only when you have the Primary Constructor in the Derived class

this() function is used to instantiate the same class constructor, we should pass right number of parameters to this() function.


open class BaseClass(var name:String){
    fun testa(){
        println("testA")
    }
}
class ChildClass(author:String):BaseClass("chercher tech"){
    constructor():this("karthiq"){
    }
    
    fun testb(){
        println("testB")
    }
}
fun main(args: Array<String>)
{
    var gc = ChildClass()
    // calling methods from base and child classes
    gc.testa()
    gc.testb()
}

We have to have this() and the super() in the constructor signature separated by :, You can have either this() or super() but not both in same class

Classes in kotlin

Types of inheritance in Kotlin:

There are four types of inheritance in kotlin, those are :

  • Single Inheritance
  • Multi-level Inheritance
  • Multiple Inheritance
  • Hybrid Inheritance

Single Inheritance in Kotlin:

When a single child class inherits the properties of a parent class, it is known as single inheritance. There are no other child classes present for that parent class. single-inheritance-kotlin

Example code for single level inheritance in kotlin.


open class BaseClass(var name:String){
    fun testa(){
        println("testA")
    }
}
class ChildClass:BaseClass("chercher tech"){
    fun testb(){
        println("testB")
    }
}
fun main(args: Array<String>)
{
    var cc = ChildClass()
    // calling methods from base and child classes
    cc.testa()
    cc.testb()
}

Default Values in the Primary Constructor

Multi-level Inheritance in Kotlin :

When a class inherits a class, which extends another class then it is called multilevel inheritance. Multilevel inheritance is nothing but the combination of more than one single inheritance

In multiple inheritance you have one path only to reach the highest class in the inheritance.

Minimum three classes are required to achieve the Multi-level inheritance in kotlin.


The last sub class will have all the properties present in its super classes.

In below example, you have only one path to reach from last sub class to top most class, Grand child class -> Child Class -> Base class

In this example, you can say that, Child Class inherits Base Class, GrandChild Class inherits from Child Class, so Grandchild inherits from Base Class, GrandChild Will have all the properties and functions from Base, Child class along with its own

multilevel-inheritance-kotlin

Example code for Multi level inheritance in kotlin.


open class BaseClass(var name:String){
    fun testa(){
        println("testA")
    }
}
open class ChildClass:BaseClass("chercher tech"){
    fun testb(){
        println("testB")
    }
}
class GrandChildClass:ChildClass(){
    fun testc(){
        println("testC")
    }
}
fun main(args: Array<String>)
{
    var gc = GrandChildClass()
    // calling methods from base and child classes
    gc.testa()
    gc.testb()
    gc.testc()
}

Properties inkotlin

Hybrid Inheritance in Kotlin:

Hybrid inheritance is the combination of every type of inheritance that exist in kotlin. As Kotlin doesn't support multiple inheritance, hybrid inheritance also can't be implemented.

If you consider the above definition then Hybrid inheritance is not possible

For most of the Kotlin people the Hybrid inheritance definition is : Combination of Single level and Multilevel inheritance.

When two classes inherit properties from a single class then it is called Hybrid inheritance.
hybrid-inheritance-kotlin


open class BaseClass(var name:String){
    fun testa(){
        println("testA")
    }
}
open class Child1Class:BaseClass("chercher tech"){
    fun testb(){
        println("testB")
    }
}
open class Child2Class:BaseClass("chercher tech"){
    fun testd(){
        println("testB")
    }
}
class GrandChildClass:Child1Class(){
    fun testc(){
        println("testC")
    }
}
fun main(args: Array<String>)
{
    var gc = GrandChildClass()
    // calling methods from base and child classes
    gc.testa()
    gc.testb()
    gc.testc()
    var c2c = Child2Class()
    c2c.testd()
    c2c.testa()
}

when with Sealed classes

Multiple Inheritance in Kotlin

Multiple inheritance is nothing but a class/interface is inheriting the properties of more than one class or interface.

A class cannot inherit the more than one class because it forms multiple paths to reach the top most class from the same last sub class.

This is where you need to remember that all the classes in kotlin are subclasses to Any class.

So Multiple inheritance is not possible, when a class tries to inherit more than one class, if class tries so, then it creates a diamond problem.

But a class can inherit one class and implement multiple interfaces and this is also called as multiple inheritance.

Similar to this Interfaces also can inherit from more than one interface, Kotlin allows multiple inheritance only because interfaces will not have any implementations

multiple-inheritance-kotlin

Type Variance in kotlin

aaaaaaaaaaaaa
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Selenium Online Training : Our next online training course for Selenium with Java starts from 17th December 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn, then you can join the course by sending email to chercher.tech@gmail.com

or Register below


 
Join My Facebook Group
Join Group