How to override a method in Kotlin

Overview

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:

  • The method that needs to be overridden should be open in nature, in the base class. We cannot override a method that is final in nature.
  • The method name and parameters should be the same in the base and derived classes.

Syntax

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
}
}
Syntax

Example

// base class
open class base {
open fun display() {
println("Function of base class")
}
}
// derived class
class derived : base() {
// override method display() of base class
override fun display() {
println("Function of derived class")
}
}
fun main() {
// instantiate derived class
val d = derived()
d.display()
}

Explanation

  • Line 2–6: We create a base class with a method display().
Note: We have marked the display() method as open.
  • Line 9: We create a derived class by inheriting the base class.
  • Line 11–12: We use the override keyword to override the display() method of the base class.

Inside the main() function,

  • Line 18: We instantiate the derived class.
  • Line 19: We call the display() method of the derived class.

Output

In the output, we can see "Function of derived class." Thus, the display() method of the base class is overridden in the derived class.