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
    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
        println("Hello Hero")

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

    //Create class Instance and Called Methods,
    //it will invoke Child class version of  methods

    //Create class Instance and Called Methods


Message for Person
Message for Child
Message for Boys
Hello Hero


Comments and Discussions



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.