文章目录
- 一、使用 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 关键字修饰
 
如果在父类中 , 被重写的函数是普通函数
'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
                










