kotlin继承的时候,在init里面调用一个被复写的方法sound,在生成子类对象调用父类的init方法时,不会调用父类的sound,而是调用子类的sound,这是因为:调用init方法的是子类对象,所以sound也是子类方法先,即使init里面是this.sound,当前对象是子类,就是调用子类的sound
open class Animal(color: String, age: Int) {
open fun sound(color: String, age: Int) {
println("Color is $color")
println("Age is $age")
}
init {
sound(color, age)
}
}
class Dog(color: String, age: Int) : Animal(color, age) {
override fun sound(color:String,age:Int){
println("Dog,color :$color,age:$age make sounds woof")
}
}
fun main(args: Array<String>) {
var d = Dog("white", 12)
d.sound("Black",11)
}
输出为:
Dog,color :white,age:12 make sounds woof
Dog,color :Black,age:11 make sounds woof
去掉子类复写的方法则符合预期
open class Animal(color: String, age: Int) {
open fun sound(color: String, age: Int) {
println("Color is $color")
println("Age is $age")
}
init {
sound(color, age)
}
}
class Dog(color: String, age: Int) : Animal(color, age) {
// override fun sound(color:String,age:Int){
// println("Dog,color :$color,age:$age make sounds woof")
// }
}
fun main(args: Array<String>) {
var d = Dog("white", 12)
d.sound("Black",11)
}
输出为:
Color is white
Age is 12
Color is Black
Age is 11