kotlin之类的继承之方法的重写

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/linzhefeng89/article/details/100714989

kotlin之类的继承之方法的重写

前言

kotlin类的继承我们使用了open关键字,但是大家会发现我们还是无法重写我们的父类的方法,因此大家需要重写父类的方法我们也需要在需要重写的方法上加上open关键字。

场景复现

首先我们先定义一个BirdOne 的类

open class BirdOne {

    var weight: Int = 10

    fun fly() {
        println("fly")
    }

}

接着我们编写一个BirdImpl然后我们使用我们的IDEA的方法的重写会发现没找到我们的fly方法
在这里插入图片描述
若我们强行在上面写我们的fly方法,会连我们的编译都无法通过。
在这里插入图片描述

实现方法的重写

直接在我们的BirdOne类的需要重写的方法上加上open关键字。

package com.kotlin.learn.cl

open class BirdOne {

    var weight: Int = 10

    open fun fly() {
        println("fly")
    }

}

接着改造我们的BirdImpl

class BirdImpl: BirdOne() {

    override fun fly() {
        println("impl-fly")
    }
}

最后我们创建一个BirdDemo来运行我们的例子

class BirdDemo {

    companion object {

        /**
         * 主入口函数
         * @JvmStatic
         */
        @JvmStatic
        fun main(args: Array<String>) {
            val birdImpl = BirdImpl()
            birdImpl.fly()
        }

    }


}

运行好以后我们会在控制台看到如下的结果,则说明方法已经被我们重写了
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/linzhefeng89/article/details/100714989