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
openin nature, in the base class. We cannot override a method that isfinalin 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 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()}
Explanation
- Line 2–6: We create a
baseclass with a methoddisplay().
Note: We have marked thedisplay()method as open.
- Line 9: We create a
derivedclass by inheriting thebaseclass. - Line 11–12: We use the
overridekeyword to override thedisplay()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.