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")
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值