Kotlin学习笔记(四)继承

作者: 大虾啊啊啊 | 来源:发表于2020-10-19 10:03 被阅读0次

1.覆盖方法

在kotlin类中所有的类都实现了超类 Any,Any不是 Java中的Object,在Any中包含了 equals() 、 hashCode() 与 toString()函数。
要创建一个可以继承的超类,需要使用open关键字。在kotlin中默认都是final的,不可继承的。

package com.example.kotlin01

open class MyUser {
    open fun say(){
        println("say MyUser")

    }
    fun see(){
        println("see MyUser")
    }
}
class MyStudent :MyUser(){
    override fun say() {
        println("say MyUser")
        super.say()
        super.see()
    }
}

fun main() {
    MyStudent().say()
}



在超类中使用open关键字来声明可以继承的方法。在子类中使用override 进行继承

2.属性覆盖

属性覆盖和方法的覆盖一样,都是通过open去声明可以覆盖的属性,然后通过override进行覆盖

open class MyUser {
    open var age = 10
}
class MyStudent :MyUser(){
    override var age = 1
}

3.调用超类实现

我们可以通过super关键字调用超类的成员。内部类可以直接调用外部类的成员,外部类可以通过super关键字并指定外部类的名字来调用外部类的超类的成员。

package com.example.kotlin01

open class MyUser {

    open fun say(){
        println("say MyUser")
    }

}
class MyStudent :MyUser(){

    override fun say() {
        println("say MyStudent")
        super.say()
    }
    //内部类调用外部类的函数,以及调用外部类的超类函数
    inner class MyParent{
        fun say2(){
            say()

        }
        fun say3(){
            super@MyStudent.say()
        }
    }
}

fun main() {
    MyStudent().MyParent().say2()
    MyStudent().MyParent().say3()

}



相关文章

网友评论

    本文标题:Kotlin学习笔记(四)继承

    本文链接:https://www.haomeiwen.com/subject/cfqkmktx.html