Saturday, 6 January 2018

Kotlin: Overriding properties

In my previous post, I explained how to override methods, overriding of properties is similar to overriding of methods.

Below step by step procedure explains, how to override a property.

Step 1: Define a variable with open modifier in Base class.
open class BaseClass {
         open var name: String = "Base Class"
}

Step 2: In sub class redefine the variable with same name using override modifier.
open class DerivedClass : BaseClass() {
         override var name: String = "Derived Class"
}

Find the below working application.

Inheritance.kt
open class BaseClass {
 open var name: String = "Base Class"
}

open class DerivedClass : BaseClass() {
 override var name: String = "Derived Class"
}

fun main(args: Array<String>) {
 var obj = DerivedClass()

 println("name : $obj.name")
}

Output

name : Derived Class

Can I override a val property with var property?
Yes, you can override a val property with a var property.


Inheritance.kt

open class BaseClass {
 open val name: String = "Base Class"
}

open class DerivedClass : BaseClass() {
 override var name: String = "Derived Class"
}

fun main(args: Array<String>) {
 var obj = DerivedClass()

 println("name : ${obj.name}")
}

Can I override a var property with val property?
No, you can’t override a var property with val property.

Inheritance.kt

open class BaseClass {
 open var name: String = "Base Class"
}

open class DerivedClass : BaseClass() {
 override val name: String = "Derived Class"
}

fun main(args: Array<String>) {
 var obj = DerivedClass()

 println("name : ${obj.name}")
}

When you try to compile above program, you will end up in below compilation error.


ERROR: Var-property public open val name: String defined in DerivedClass cannot be overridden by val-property public open var name: String defined in BaseClass (6, 11)





Previous                                                 Next                                                 Home

No comments:

Post a Comment