BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Kotlin Inheritance with examples

By Chaitanya Singh | Filed Under: Kotlin Tutorial

Inheritance is a feature using which a class inherits all the features of another class. The class from which the features are inherited is known as base class or super class or parent class and the class that inherits the features is known as derived class or sub class or child class. In this guide, we will learn what is inheritance and how to implement it in the Kotlin with the help of examples.

What is Inheritance and why we need it?

Lets say we have three classes Dog, Cat and Horse. All of these three classes have some properties (Data members) and some behaviours (member functions). We have depicted the properties and behaviours of these classes in the following diagram.
Kotlin Inheritance

We can see in the diagram that these three classes have few properties and behaviours common, why not make a generalized class with the common properties and behaviours and let these three classes inherit that generalized class. In addition these classes can have their unique properties and behaviours apart from the inherited ones.

Kotlin inheritance example

So Dog class now inherits all the features of Animal class and adds an additional feature woof(), similarly Cat class inherits all the features of Animal class and adds its unique feature meow() and so on.

Lets write this logic in a Kotlin program.

Note: By default all classes in Kotlin are final so you have to use the open annotation in the parent class, this tells the compiler that this class can be inherited by other classes.

open class Animal(colour: String, age: Int) {
    init {
        println("Color is: $colour.")
        println("Age is: $age")
    }
}

class Dog(colour: String, age: Int): Animal(colour, age) {

    fun woof() {
        println("Dog makes sound of woof")
    }
}

class Cat(colour: String, age: Int): Animal(colour, age) {

    fun meow() {
        println("Cat makes sound of meow")
    }
}

class Horse(colour: String, age: Int): Animal(colour, age) {

    fun neigh() {
        println("Horse makes sound of neigh")
    }
}

fun main(args: Array<String>) {
    val d = Dog("Black",4)
    d.woof()
    val c = Cat("White", 1)
    c.meow()
    val h = Horse("Brown", 8)
    h.neigh()
}

Output:
Kotlin inheritance example

Overriding member functions and properties in Kotlin

If a function or property with the same name exist in the child class then we need to override the them in child class using override keyword.

Overriding member function

A child class can override the member function of parent class using override keyword. By overriding a function, a child class gives its own implementation to the already existing code of base class. Overriding doesn’t mean that it will update the code in base class, the change is only applicable to the class overriding the function or its sub classes. Lets take an example.

open class Animal() {
    open fun sound() {
        println("Animal makes a sound")
    }
}

class Dog: Animal() {
    override fun sound() {
        println("Dog makes a sound of woof woof")
    }
}

fun main(args: Array<String>) {
    val d = Dog()
    d.sound()
}

Output:

Dog makes a sound of woof woof

Overriding properties (data members) of base class

We can override the property of base class, similar to what we have seen above for member function. In the following example we have a property colour in the parent class and we are overriding it in the child class.

open class Animal() {
    open var colour: String = "White"
}

class Dog: Animal() {
    override var colour: String = "Black"
    fun sound() {
        println("Dog makes a sound of woof woof")
    }
}

fun main(args: Array<String>) {
    val d = Dog()
    d.sound()
    println("${d.colour}")
}

Output:

Dog makes a sound of woof woof
Black

Calling data members and member functions of base class from child class

In the following example we are calling the data member num and member function demo() of Parent class from the Child class using super keyword.

open class Parent() {
    open var num: Int = 100
    open fun demo(){
        println("demo function of parent class")
    }
}

class Child: Parent() {
    override var num: Int  = 101
    override fun demo() {
        super.demo()
        println("demo function of child class")
    }
    fun demo2(){
        println(super.num)
    }
}

fun main(args: Array<String>) {
    val obj = Child()
    obj.demo()
    obj.demo2()
}

Output:

demo function of parent class
demo function of child class
100
❮ PreviousNext ❯

Comments

  1. David Kayode Idowu says

    September 20, 2019 at 11:05 AM

    very concise and easy explanation.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Kotlin Tutorial

  • Kotlin Tutorial
  • Kotlin in Eclipse IDE
  • Kotlin in IntelliJ
  • First Kotlin Program
  • Kotlin Keywords
  • Kotlin Variables
  • Kotlin Type Casting
  • Kotlin operators
  • Kotlin Input/Output
  • Kotlin Comments

Kotlin String

  • Kotlin String

Kotlin Array

  • Kotlin Array
  • Kotlin Range

Control Flow

  • Kotlin if expression
  • Kotlin when expression
  • Kotlin for loop
  • Kotlin while loop
  • Kotlin do-while loop
  • Kotlin continue
  • Kotlin break

Kotlin Function

  • Kotlin Function
  • Kotlin Recursion
  • Kotlin default and named arguments
  • Lambda functions
  • Higher Order Function

Exception Handling

  • Exception Handling
  • Kotlin try catch
  • Multiple catch blocks
  • Nested try catch
  • Throw keyword
  • Kotlin try expression

Kotlin OOP

  • Class and Objects
  • Kotlin Constructors
  • Kotlin Inheritance
  • Visibility Modifiers
  • Kotlin abstract class
  • Kotlin Interfaces
  • Nested and Inner Class
  • Kotlin Data Class
  • Kotlin Sealed Class

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap