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 classopen class base {open val value: Int = 5}// derived classclass derived : base() {// overriding property value of base classoverride val value: Int = 10}fun main() {// instantiating base classval b = base()// printing property value of base classprintln("Value in base class: ${b.value}")// instantiating derived classval d = derived()// printing property value of derived classprintln("Value in derived class: ${d.value}")}
Explanation
- Lines 2–4: We create a class
basewith a propertyvalue.
Note: We have marked the property
valueasopen.
- Line 7: We create a
derivedclass by inheriting thebaseclass. - Line 9: We use the
overridekeyword to override the propertyvalueof the base class.
Inside the main() function:
- Line 14: We instantiate an object of the
baseclass. - Line 16: We print the property
valueof thebaseclass objectbto the console.
- Line 19: We instantiate an object of the
derivedclass. - Line 21: We print the property
valueof thederivedclass objectdto 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 .