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
    //overridable
    open fun printMessage(){
        println("Message for Person")
    }
}

//Derived class extends Person class
class Child: Person() {
    //Override base class methods
    override 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 final
        final override fun printMessage(){
            println("Message for Boys")
        }
}

//Derived class
class Hero : Boy() {
    //Declare member function
    fun printData(){
        //calling , Boy Class Implementation 
        //of printMessage() function
        super.printMessage()
        println("Hello Hero")
    }
}


fun main(args:Array<String>){
    //Create Person class Instance and Called Methods, 
    //it will invoke Base class version of  methods
    Person().printMessage()

    //Create class Instance and Called Methods,
    //it will invoke Child class version of  methods
    Child().printMessage()

    //Create class Instance and Called Methods
    Hero().printData()
}

Output:

输出:

Message for Person
Message for Child
Message for Boys
Hello Hero


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

kotlin 覆盖属性

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值