Kotlin 继承
Kotlin 继承(子类和超类)
在 Kotlin 中,可以将一个类的属性和函数继承到另一个类。我们将“继承概念”分为两类
- subclass(子类) - 继承自另一个类的类
- superclass(超类) - 被继承的类
在下面的例子中,MyChildClass
(子类)继承了 MyParentClass
类(超类)的属性
示例
// Superclass
open class MyParentClass {
val x = 5
}
// Subclass
class MyChildClass: MyParentClass() {
fun myFunction() {
println(x) // x is now inherited from the superclass
}
}
// Create an object of MyChildClass and call myFunction
fun main() {
val myObj = MyChildClass()
myObj.myFunction()
}
自己动手试一试 »
示例解释
在超类/父类前使用 open
关键字,使其成为其他类应该继承属性和函数的类。
要从一个类继承,请指定子类的名称,后跟一个冒号 :
,然后是超类的名称。
为何以及何时使用“继承”?
- 这对于代码重用很有用:在创建新类时重用现有类的属性和函数。