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.
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}
// 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}")}
base
with a property value
.Note: We have marked the property
value
asopen
.
derived
class by inheriting the base
class.override
keyword to override the property value
of the base class.Inside the main()
function:
base
class.value
of the base
class object b
to the console.derived
class.value
of the derived
class object d
to the console.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
.