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 覆盖属性