Kotlin program | Example of method overriding

Kotlin | Method Overriding: Here, we are implementing a Kotlin program to demonstrate the example of method overriding.
Submitted by IncludeHelp, on June 03, 2020

Method Overriding

  • Method overriding allows derived class has the same function name and signature as the base class
  • By method overriding we can provide different implementation into the derived class of base class methods.
  • By default method is final in Kotlin class, to make them overridable declare the method with 'open'
  • The open modifier does not affect when added on members of a final class (i.e.. a class with no open modifier).
  • Marked function with 'override' into derived class while overriding the base class method.
  • Use 'super' to call the base class implementation of the method from child class

Program for method overriding in Kotlin

package com.includehelp

//Declare Base class, 
//marked with 'open' to make inheritable
open class Person{
    //marked function with 'open' to make
    //overridable
    open fun printMessage(){
        println("Message for Person")
    }
}

//Derived class extends Person class
class Child: Person() {
    //Override base class methods
    override fun printMessage(){
        println("Message for Child")
    }
}

//marked derived class with 'open' 
//to make further inheritable by its 
//child class
open class Boy : Person(){
        //A member marked override is itself open, 
        //i.e. it may be overridden in subclasses.
        //If you want to prohibit re-overriding, use final
        final override fun printMessage(){
            println("Message for Boys")
        }
}

//Derived class
class Hero : Boy() {
    //Declare member function
    fun printData(){
        //calling , Boy Class Implementation 
        //of printMessage() function
        super.printMessage()
        println("Hello Hero")
    }
}


fun main(args:Array<String>){
    //Create Person class Instance and Called Methods, 
    //it will invoke Base class version of  methods
    Person().printMessage()

    //Create class Instance and Called Methods,
    //it will invoke Child class version of  methods
    Child().printMessage()

    //Create class Instance and Called Methods
    Hero().printData()
}

Output:

Message for Person
Message for Child
Message for Boys
Hello Hero


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.