How to override a property in Kotlin

Overview

Property overriding means redefining or modifying the property of the base class in its derived class. Thus, it can be only achieved in inheritance. The property that needs to be overridden should be open in nature, in the base class. We cannot override a method that is final in nature.

Syntax

To override a property of the base class in the derived class, we use the override keyword.

open class base {
open val value: Int = 5
}
class derived : base() {
override val value: Int = 10
}
Syntax

Example

// base class
open class base {
open val value: Int = 5
}
// derived class
class derived : base() {
// overriding property value of base class
override val value: Int = 10
}
fun main() {
// instantiating base class
val b = base()
// printing property value of base class
println("Value in base class: ${b.value}")
// instantiating derived class
val d = derived()
// printing property value of derived class
println("Value in derived class: ${d.value}")
}

Explanation

  • Lines 2–4: We create a class base with a property value.

Note: We have marked the property value as open.

  • Line 7: We create a derived class by inheriting the base class.
  • Line 9: We use the override keyword to override the property value of the base class.

Inside the main() function:

  • Line 14: We instantiate an object of the base class.
  • Line 16: We print the property value of the base class object b to the console.
  • Line 19: We instantiate an object of the derived class.
  • Line 21: We print the property value of the derived class object d to the console.

Output

In the output, we can see that the value in base is 5, whereas the value in derived is 10. Thus, the property value of base is overridden in derived .

Free Resources