本文共 2322 字,大约阅读时间需要 7 分钟。
kotlin 覆盖属性
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”从子类中调用方法的基类实现
package com.includehelp//Declare Base class, //marked with 'open' to make inheritableopen class Person{ //marked function with 'open' to make //overridable open fun printMessage(){ println("Message for Person") }}//Derived class extends Person classclass 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 classopen 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 classclass Hero : Boy() { //Declare member function fun printData(){ //calling , Boy Class Implementation //of printMessage() function super.printMessage() println("Hello Hero") }}fun main(args:Array){ //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 PersonMessage for ChildMessage for BoysHello Hero
翻译自:
kotlin 覆盖属性
转载地址:http://zhxzd.baihongyu.com/