【Kotlin】类的继承①(使用open关键字开启类的继承|使用open关键字开启方法重写)
- 开源代码
- 2025-08-20 14:57:02

文章目录 一、使用 open 关键字开启类的继承二、使用 open 关键字开启方法重写 一、使用 open 关键字开启类的继承
Kotlin 中的类 默认都是 封闭的 , 无法被继承 , 如果要想类被继承 , 需要在定义类时 使用 open 关键字 ;
定义一个普通的 Kotlin 类 :
class Person(val name: String, val age: Int) { fun info() { println("name : $name, age : $age") } fun sayHello(){ println("Hello World") } }此时 , 如果声明一个类 , 继承 普通的 kotlin 类 , 在编译时会提示
This type is final, so it cannot be inherited from报错信息 ;
如果使用 open 关键字 修饰 Person 类 , 则该类可以被继承 , 此时报错信息消失 ;
代码示例 :
open class Person(val name: String, val age: Int) { fun info() { println("name : $name, age : $age") } fun sayHello(){ println("Hello World") } } class Student : Person("Tom", 18){ } fun main() { var student = Student() student.info() student.sayHello() }上述代码执行结果 :
name : Tom, age : 18 Hello World 二、使用 open 关键字开启方法重写在 Kotlin 类的子类中 , 使用 override 关键字 重写方法 , 格式为 :
override fun 被重写的方法名(参数列表): 返回值类型 { // 方法体 }注意 , 父类中 被重写方法 必须 使用 open 关键字修饰 , 才能开启方法重写 , 否则默认情况下方法是 final 类型的 ;
如果在父类中 , 被重写的函数是普通函数 , 没有使用 open 关键字修饰 , 重写该函数就会出现如下报错 :
'sayHello' in 'Person' is final and cannot be overridden在 父类 Person 类中 , sayHello 函数是普通函数 , 默认情况下普通函数不能被重写 , 因此报上述错误 ;
在 父类中 , 使用 open 关键字 , 开启函数重写 , 在编译时就不会进行报错 ;
正确代码示例 :
open class Person(val name: String, val age: Int) { fun info() { println("name : $name, age : $age") } open fun sayHello(){ println("Hello World") } } class Student : Person("Tom", 18){ override fun sayHello(){ println("Hello World Tom") } } fun main() { var student = Student() student.info() student.sayHello() }执行结果 :
name : Tom, age : 18 Hello World Tom【Kotlin】类的继承①(使用open关键字开启类的继承|使用open关键字开启方法重写)由讯客互联开源代码栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“【Kotlin】类的继承①(使用open关键字开启类的继承|使用open关键字开启方法重写)”