kotlin 覆盖属性_Kotlin程序| 覆盖属性示例

kotlin 覆盖属性

覆盖属性 (Overriding Properties)

  • Overriding properties works similarly to overriding methods.

    覆盖属性的作用类似于覆盖方法。

  • Superclass properties, that are redeclared in derived class must be prefaced with 'override'.

    在派生类中重新声明的超类属性必须以“ override”开头。

  • Also, override val property with var but not vice versa. You can use override in property declaration in a primary constructor.

    同样,用var覆盖val属性,反之亦然。 您可以在主构造函数的属性声明中使用override。

  • By default properties are final in Kotlin class, to make them overridable declare the method with 'open'

    默认情况下,属性是Kotlin类中的final属性,以使其可重写以使用'open'声明方法

程序演示Kotlin中覆盖属性的示例 (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


翻译自: https://www.includehelp.com/kotlin/example-of-overriding-properties.aspx

kotlin 覆盖属性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值