Kotlin 派生类

1、超类

Any Kotlin 中所有类的默认超类,有三个方法:equals()、 hashCode() 与 toString()

class Example // 从 Any 隐式继承
2、继承

默认情况下,Kotlin 类是最终(final)的——它们不能被继承

open 关键字标记类可继承

open class Base // 该类开放继承

类继承的语法:派生类类 

// 派生类有一个主构造函数,其基类必须根据其参数在该主构造函数中初始化
open class Base(p: Int)            // 基类
class Derived(p: Int) : Base(p)    // 派生类

// 派生类没有主构造函数,那么每个次构造函数必须使用super 关键字初始化其基类型
// 或委托给另一个做到这点的构造函数
class MyView : View {
    constructor(ctx: Context) : super(ctx)
    constructor(ctx: Context, attrs: AttributeSet) : super(ctx, attrs)
}
 3、覆盖方法

override 修饰符,覆盖使用open标注的成员;open 修饰符final 类(即没有 open 的类) 的成员失效不起作用

open class Shape {                      // 这个open,表示类允许继承
    open fun draw() { /*……*/ }          // 这个open,表示方法允许覆盖
    fun fill() { /*……*/ }
}

class Circle() : Shape() {               // final类Circle继承自Shape
    override fun draw() { /*……*/ }       // 覆盖基类的draw方法
}

open class Rectangle() : Shape() {       // open类Rectangle继承自Shape
    final override fun draw() { /*……*/ } // 覆盖基类的draw方法,并且禁止Rectangle的派生类覆盖
}
4、覆盖属性

属性方法覆盖机制相同,每个声明的属性可以由具有初始化器的属性或者具有 get 方法的属性覆盖

open class Shape {
    open val vertexCount: Int = 0
}

class Rectangle : Shape() {
    override val vertexCount = 4
}
interface Shape {
    val vertexCount: Int
}

// 子类1 在主构造函数中使用 override 声明覆盖属性
class Rectangle(override val vertexCount: Int = 4) : Shape

// 子类2 
class Polygon : Shape {
    override var vertexCount: Int = 0  // var 属性可覆盖 val 属性,但反之则不行
}
5、调用超类实现

派生类中的代码可用 super 关键字调用超类函数与属性访问器的实现

open class Rectangle {
    open fun draw() { println("Drawing a rectangle") }
    val borderColor: String get() = "black"
}

class FilledRectangle : Rectangle() {
    override fun draw() {
        super.draw()
        println("Filling the rectangle")
    }

    val fillColor: String get() = super.borderColor
}

inner 内部类中访问外部类的超类,可用由外部类名限定的 super 关键字来实现:super@Outer 

open class Rectangle {
    open fun draw() { println("Drawing a rectangle") }
    val borderColor: String get() = "black"
}

class FilledRectangle: Rectangle() {
    override fun draw() {
        val filler = Filler()
        filler.drawAndFill()
    }

    inner class Filler {
        fun fill() { println("Filling") }
        fun drawAndFill() {
            super@FilledRectangle.draw() // 调用 Rectangle 的 draw() 实现
            fill()
            // 使用 Rectangle 所实现的 borderColor 的 get()
            println("Drawn a filled rectangle with color ${super@FilledRectangle.borderColor}")
        }
    }
}
6、覆盖规则

继承规则:如果一个类从它的直接超类继承相同成员多个实现,它必须覆盖这个成员提供其自己的实现(也许用继承来的其中之一);如需表示采用从哪个超类型继承的实现,请使用由尖括号中超类型名限定的 super 

open class Rectangle {
    open fun draw() { /* …… */ }
}

interface Polygon {
    fun draw() { /* …… */ } // 接口成员默认就是“open”的
}

// 可以同时继承 Rectangle 与 Polygon, 但是二者都有各自的 draw() 实现
// 必须在 Square 中覆盖 draw(), 并为其提供一个单独的实现以消除歧义
class Square() : Rectangle(), Polygon {
    // 编译器要求覆盖 draw():
    override fun draw() {
        super<Rectangle>.draw() // 调用 Rectangle.draw()
        super<Polygon>.draw() // 调用 Polygon.draw()
    }
}
7、初始化顺序

构造派生类的新实例时,首先完成其基类初始化 (基类构造函数执行时,派生类中声明或覆盖的属性都还没有初始化;在基类初始化逻辑中(直接或者通过另一个覆盖的 open 成员的实现间接)使用任何一个这种属性,都可能导致不正确的行为或运行时故障;因此设计一个基类时,应该避免在构造函数、属性初始化器或者 init 块中使用 open 成员

open class Base(val name: String) {
    init { println("Initializing a base class") }

    open val size: Int = 
        name.length.also { println("Initializing size in the base class: $it") }
}

class Derived(
    name: String,
    val lastName: String,
) : Base(name.replaceFirstChar { it.uppercase() }.also { println("Argument for the base class: $it") }) {
    init { println("Initializing a derived class") }

    override val size: Int =
        (super.size + lastName.length).also { println("Initializing size in the derived class: $it") }
}

fun main() {
    println("Constructing the derived class(\"hello\", \"world\")")
    Derived("hello", "world")
}

 

 

相关推荐

  1. Kotlin 派生

    2023-12-29 07:58:01       52 阅读
  2. Kotlin

    2023-12-29 07:58:01       60 阅读
  3. Kotlin-

    2023-12-29 07:58:01       53 阅读
  4. C++ 入门10:继承和派生

    2023-12-29 07:58:01       17 阅读
  5. 第五章 的继承与派生之——的继承与派生

    2023-12-29 07:58:01       45 阅读
  6. C++派生对基成员的访问

    2023-12-29 07:58:01       24 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-29 07:58:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-29 07:58:01       101 阅读
  3. 在Django里面运行非项目文件

    2023-12-29 07:58:01       82 阅读
  4. Python语言-面向对象

    2023-12-29 07:58:01       91 阅读

热门阅读

  1. Go面试题学习

    2023-12-29 07:58:01       65 阅读
  2. Leetcode 509 斐波那契数

    2023-12-29 07:58:01       46 阅读
  3. 什么是ETL?

    2023-12-29 07:58:01       54 阅读
  4. 【Delphi 基础知识 4】类是如何被实例化的?

    2023-12-29 07:58:01       62 阅读
  5. win10 vs c++ 安装vcpkg 类似于pip

    2023-12-29 07:58:01       59 阅读
  6. 案例系列:IBM反洗钱交易数据_GNN节点分类检测

    2023-12-29 07:58:01       43 阅读
  7. 数据库是否可以直接作为数据仓库的数据源

    2023-12-29 07:58:01       53 阅读