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
Program for method overriding in Kotlin
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer