Method overriding means to redefine or modify the method of the base class in its derived class. Thus, it can be only achieved in Inheritance.
Following are the conventions that need to be followed for method overriding in Kotlin:
open
in nature, in the base class. We cannot override a method that is final
in nature.To override a method of the base class in the derived class, we use the override
keyword followed by the fun
keyword and the method name to be overridden.
open class base {open fun functionName() {// body}}class derived : base() {override fun functionName() {// body}}
// base classopen class base {open fun display() {println("Function of base class")}}// derived classclass derived : base() {// override method display() of base classoverride fun display() {println("Function of derived class")}}fun main() {// instantiate derived classval d = derived()d.display()}
base
class with a method display()
.Note: We have marked thedisplay()
method as open.
derived
class by inheriting the base
class.override
keyword to override the display()
method of the base class.Inside the main()
function,
display()
method of the derived class.In the output, we can see "Function of derived class." Thus, the display()
method of the base class is overridden in the derived class.