iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 10
0
Software Development

初探Kotlin系列 第 10

[Day 10] Classes and Inheritance-2

Inheritance

Kotlin所有的類別最上層都繼承Any 就如同Java最上層都是繼承Object一樣
Any跟Java的Object不一樣 Any除了equals(), hashCode(),toString()沒有其他的成員

class Example

上述類別默許就繼承Any

Kotlin繼承方式如下

open class Base(p: Int)

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

如果子類別有primary constructor 則必須使用子類的primary constructor的參數完成父類的初始化
如果子類沒有primary constructor則必須在secondary constructor中使用super關鍵字完成父類初始化

class MyView : View {
    constructor(ctx: Context) : super(ctx)

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

Overriding Methods

Kotlin中所有類別預設都是final的,也就是不可被繼承
想要被繼承的類別需要使用open關鍵字

open class Base {
    open fun v() {}
    fun nv() {}
}
class Derived() : Base() {
    override fun v() {}
}

想要overridin*Base.v()*的話 就必須要有open的關鍵字
反之 不想被繼承的話則可宣告final

open class AnotherDerived() : Base() {
    final override fun v() {}
}

Overriding Properties

Overriding Properties跟Overriding Methods方式差不多

open class Foo {
open val x: Int get { ... }
}

class Bar1 : Foo() {
override val x: Int = ...
}

val的屬性可以overrid為var,反之則不行


上一篇
[Day 9] Classes and Inheritance-1
下一篇
[Day 11] Classes and Inheritance-3
系列文
初探Kotlin19
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言