Property-overriding 

Kotlin also allows us to override class properties to provide new definitions. Overriding the property is similar to overriding the function: the property must be declared as open in the parent class and the override keyword must be used in the child class to make sure that the property is being overridden explicitly and not accidentally.

Property-overriding is possible in the following cases:

  • Immutable properties can be overridden by immutable properties 
  • Immutable properties can be overridden by mutable properties
  • Mutable properties can be overridden by mutable properties

We can override the val properties with either the val or var properties, and we can override the var properties with other var properties, but var properties cannot be overridden with val properties.

Let's take a look at the following example. The Programming class, which has one read property, name, and one function, info(), is derived by the AdvancedProgramming child class.

The child class overrides the name property and changes the property type from val to var:

open class Programming (open val name: String){
open fun info(){
println("Programming language $name")
}
}

class AdvancedProgramming(override var name : String) : Programming(name){
override fun info(){
println("Advanced Programming language $name")
}
}

In the main function, we will create an object of the Programming class with one parameter, Java. As we can see, the name property is declared as immutable and cannot be changed:

fun main(args: Array<String>) {

var programming = Programming("Java")
// name is read only
// programming.name = "Kotlin"
programming.info()

var advancedProgramming = AdvancedProgramming("Kotlin")
advancedProgramming.info()

// name is read-write
advancedProgramming.name = "Kotlin 2.0"
advancedProgramming.info()
}

When we change the property type to mutable by overriding it in the AdvancedProgramming class, the property can be reassigned as many times as we need:

The object of the Programming class does not allow us to change the value of the name property. The value of name in the child class can be updated, however, because the property has been overridden from immutable to mutable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.63.95