Q:

Kotlin program | Example of Overriding Properties

belongs to collection: Kotlin Class and Object Programs

0

Overriding Properties

  • Overriding properties works similarly to overriding methods.
  • Superclass properties, that are redeclared in derived class must be prefaced with 'override'.
  • Also, override val property with var but not vice versa. You can use override in property declaration in a primary constructor.
  • By default properties are final in Kotlin class, to make them overridable declare the method with 'open'

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to demonstrate the example of overriding properties in Kotlin

package com.includehelp

// Declare Base class , marked with 'open' 
// to make inheritable
open class ABC{
    // marked property with 'open' 
    // to make overridable
    open val a=10

    init {
        println("Init Block : Base Class")
        println("Value : $a")
    }
}

// Derived class extends Base class
open class XYZ: ABC() {
    // Override base class property
    override var a=15
    init {
        println("Init Block : Child Class 1")
    }
}


// Derived class with primary constructor
// Override base class property as 
// parameter in primary constructor
class PQR(override var a:Int): XYZ() {
    init {
        println("Init Block : Child Class 2")
        println("Value : $a")

        // Access Super class value of 
        // property using super keyword
        println("Super class value : ${super.a}")
    }
}

// Main function, Entry Point of program
fun main(args: Array<String>){
    // Create Instance of PQR class
    val abc:ABC = PQR(20)
}

Output:

Init Block : Base Class
Value : 0
Init Block : Child Class 1
Init Block : Child Class 2
Value : 20
Super class value : 15

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin program | Example of Properties Getter and ... >>
<< Kotlin program | Example of Resolving Overriding C...