Kotlin的open关键字的一些想法

164 阅读1分钟

kotlin常学常新,看我不卷死你们

open在kotlin中用于继承

open class Person {
    open fun eat() {
        println("Person eat")
    }
    fun run() {
        println("Person run")
    }
}

class Student : Person() {
    override fun eat() {
        super.eat()
        println("Student eat")
    }
}

fun main() {
    val p = Person()
    val s = Student()
    p.eat()
    p.run()
    s.eat()
    s.run()
}

父类Person有两个方法eat和run。子类Student继承Person,重载方法eat。运行的结果

Person eat
Person run
Person eat
Student eat
Person run

第一第二行是p对象的执行,第三第四和第五行是s对象的执行。第三行的Person eat是因为Student的eat方法中执行了super.eat,走了一遍父类的eat方法。

Tips:刚开始的时候用Log代替println,结果报错了,

Exception in thread "main" java.lang.RuntimeException: Stub!

原来Log是Android专门的方法,Java中没有这个方法。

对,以上都是常规用法。在kotlin中,或者说Java8中,有一种写法,叫匿名类。

open class Person {
    open fun eat() {
        println("Person eat")
    }
    fun run() {
        println("Person run")
    }
}

class Student : Person() {
    override fun eat() {
        println("Student eat")
        super.eat()
    }
}

fun main() {
    val d = object : Person() {
        override fun eat() {
            super.eat()
            println("d eat")
        }
    }
    d.eat()
}

此时输出为

Person eat
d eat

在main中创建匿名类并由d持有,方法等同于创建Student类的创建。这适用于那些只使用一次的类的场景,方面快捷。 同样的,利用这种方法,可以实现类似接口回调的效果,节省了一个接口。

真的是常学常新啊!