kotlin 覆盖属性_Kotlin程序| 方法覆盖的示例
kotlin 覆蓋屬性
方法重載 (Method Overriding)
Method overriding allows derived class has the same function name and signature as the base class
方法重寫允許派生類具有與基類相同的函數名稱和簽名
By method overriding we can provide different implementation into the derived class of base class methods.
通過方法重寫,我們可以為基類方法的派生類提供不同的實現。
By default method is final in Kotlin class, to make them overridable declare the method with 'open'
默認情況下,方法在Kotlin類中是final,要使其可重寫,請使用“ open”聲明該方法
The open modifier does not affect when added on members of a final class (i.e.. a class with no open modifier).
當將open修飾符添加到最終類的成員(即沒有open修飾符的類)的成員上時,則不受影響。
Marked function with 'override' into derived class while overriding the base class method.
在覆蓋基類方法的同時,將具有“覆蓋”功能的標記為派生類。
Use 'super' to call the base class implementation of the method from child class
使用“ super”從子類中調用方法的基類實現
Kotlin中的方法重寫程序 (Program for method overriding in Kotlin)
package com.includehelp//Declare Base class, //marked with 'open' to make inheritable open class Person{//marked function with 'open' to make//overridableopen fun printMessage(){println("Message for Person")} }//Derived class extends Person class class Child: Person() {//Override base class methodsoverride fun printMessage(){println("Message for Child")} }//marked derived class with 'open' //to make further inheritable by its //child class open class Boy : Person(){//A member marked override is itself open, //i.e. it may be overridden in subclasses.//If you want to prohibit re-overriding, use finalfinal override fun printMessage(){println("Message for Boys")} }//Derived class class Hero : Boy() {//Declare member functionfun printData(){//calling , Boy Class Implementation //of printMessage() functionsuper.printMessage()println("Hello Hero")} }fun main(args:Array<String>){//Create Person class Instance and Called Methods, //it will invoke Base class version of methodsPerson().printMessage()//Create class Instance and Called Methods,//it will invoke Child class version of methodsChild().printMessage()//Create class Instance and Called MethodsHero().printData() }Output:
輸出:
Message for Person Message for Child Message for Boys Hello Hero翻譯自: https://www.includehelp.com/kotlin/example-of-method-overriding.aspx
kotlin 覆蓋屬性
總結
以上是生活随笔為你收集整理的kotlin 覆盖属性_Kotlin程序| 方法覆盖的示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 狮子多少钱一只啊?
- 下一篇: 创世神话怎么打宝石?