Kotlin program | Example of Overriding Properties

Kotlin | Overriding Properties: Here, we are implementing a Kotlin program to demonstrate the example of overriding properties.
Submitted by IncludeHelp, on June 08, 2020

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'

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


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.