首页 Kotlin学习笔记(4) - 继承
文章
取消

Kotlin学习笔记(4) - 继承

## 一、继承

在Kotlin中所有类的公共超类是Any,对于没有声明超类的默认会继承Any

Any具有三个方法equals(),hashCode(),toString()

默认情况下Kotlin类是final的,不允许继承,如果需要被继承可以使用open关键字进行修饰

1
open class Base // Class is open for inheritance

显式的继承超类,使用冒号放在类后面

1
2
3
open class Base(p: Int)

class Derived(p: Int) : Base(p)

如果派生类没有主构造函数的话每个辅助构造函数都需要使用super关键字初始化基类或委托给另一个具有主构造函数的函数

1
2
3
4
5
class MyView : View {
    constructor(ctx: Context) : super(ctx)

    constructor(ctx: Context, attrs: AttributeSet) : super(ctx, attrs)
}

二、方法重写

Kotlin中默认是允许进行重写点,需要加open关键字进行修饰,子类中重写方法需要加override关键字

1
2
3
4
5
6
7
8
open class Shape {
    open fun draw() { /*...*/ }
    fun fill() { /*...*/ }
}

class Circle() : Shape() {
    override fun draw() { /*...*/ }
}

如果子类重写后,不希望其他自己的子类继续覆盖的话可加final修饰符

1
2
3
open class Rectangle() : Shape() {
    final override fun draw() { /*...*/ }
}

三、属性重写

与方法重新类似

1
2
3
4
5
6
7
open class Shape {
    open val vertexCount: Int = 0
}

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

可以使用var属性去覆盖val属性,但反之是不行的,也可以在主构造函数中直接覆盖

1
2
3
4
5
6
7
8
9
interface Shape {
    val vertexCount: Int
}

class Rectangle(override val vertexCount: Int = 4) : Shape // Always has 4 vertices

class Polygon : Shape {
    override var vertexCount: Int = 0  // Can be set to any number later
}

四、初始化顺序

基类的初始化会优先于子类,需要基类初始化块中用到的一些属性如果被子类覆盖了的话可能会引发一些问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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")
}

// print ------------
//Constructing the derived class("hello", "world")
//Argument for the base class: Hello
//Initializing a base class
//Initializing size in the base class: 5
//Initializing a derived class
//Initializing size in the derived class: 10


五、调用超类

子类中可以通过super关键字调用超类中的方法或属性

1
2
3
4
5
6
7
8
9
10
11
12
13
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
}

在子类的内部类中访问基类的属性或方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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() // Calls Rectangle's implementation of draw()
            fill()
            println("Drawn a filled rectangle with color ${super@FilledRectangle.borderColor}") // Uses Rectangle's implementation of borderColor's get()
        }
    }
}

fun main() {
    val fr = FilledRectangle()
        fr.draw()
}

六、重写的一些规则

如果超类中可能有多个实现具有同名的方法,可以在子类中使用super<Base>来确定具体调用那个实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
open class Rectangle {
    open fun draw() { /* ... */ }
}

interface Polygon {
    fun draw() { /* ... */ } // interface members are 'open' by default
}

class Square() : Rectangle(), Polygon {
    // The compiler requires draw() to be overridden:
    override fun draw() {
        super<Rectangle>.draw() // call to Rectangle.draw()
        super<Polygon>.draw() // call to Polygon.draw()
    }
}
本文由作者按照 CC BY 4.0 进行授权

Kotlin学习笔记(3) - 类

Kotlin学习笔记(5) - 属性