Kotlin中的类默认是final类型的,想要被继承,得用“open”关键字修饰。
open class Shape {}
class Rectangle : Shape {}
子类的所有构造构造方法必须直接或间接调用一个父类的构造方法
open class Shape {
constructor(name: String) {
print(name)
}
}
class Rectangle : Shape {
constructor(name: String) : super(name) {}
constructor(name: String, age: Int) : this(name) {}
}
子类的所有构造构造方法必须直接或间接调用一个父类的构造方法
open class Shape {
constructor(name: String) {
print(name)
}
}
class Rectangle : Shape {
constructor(name: String) : super(name) {}
constructor(name: String, age: Int) : this(name) {}
}
成员方法重写
继承过程中,只有open修饰的方法才能被重写,重写时要用override修饰。
open特性也能被继承,想要断了open特性,只需用final修饰即可。
open class Shape {
open fun method() {}
}
open class Rectangle : Shape() {
override fun method() {}
}
class Square : Rectangle() {
final override fun method() {}
}
成员变量重写
与方法重写相同,只有open修饰的变量才能被重写,open同样可以继承,也可以用final中断。
重写过程中,变量可由val类型变为var类型,反之则不行。
open class Shape {
open val name: String = "Shape"
}
open class Rectangle : Shape() {
override var name: String = "Rectangle"
}
class Square : Rectangle() {
final override var name = "Square"
}
调用父类方法和变量
- 可通过“super”关键字调用父类的方法和成员变量
open class Shape {
open val name: String = "Shape"
open fun draw() {}
}
open class Rectangle : Shape() {
override var name: String = super.name
override fun draw() {
super.draw()
}
}
- 内部类调用外部类父类的方法 使用“super@Outer”方式:
open class Sup {
open fun method() { println("Sup.method") }
}
class Sub:Sup(){
inner class Inner{
fun test(){
super@Sub.method()
}
}
}
- 当继承的类和接口当中出现相同的方法(方法名和参数都相同),通过类似泛型的方法明确调用哪个方法
interface Action {
fun eat() {
println("Action")
}
}
open class Animal {
open fun eat() {
println("Animal")
}
}
class Human() : Animal(), Action {
override fun eat() {
super<Action>.eat()
super<Animal>.eat()
}
}