Kotlin 有没有办法用声明类型的子类型重写抽象属性?
考虑以下示例:我有一个动物的抽象类,每个动物都有一张嘴,但因为每个动物的嘴都不同,所以嘴类也是抽象的:Kotlin 有没有办法用声明类型的子类型重写抽象属性?,kotlin,polymorphism,abstract-class,Kotlin,Polymorphism,Abstract Class,考虑以下示例:我有一个动物的抽象类,每个动物都有一张嘴,但因为每个动物的嘴都不同,所以嘴类也是抽象的: abstract class Animal { var numberLegs: Int = 4 var mouth: Mouth? = null } abstract class Mouth { abstract fun makeSound() } 我现在可以创建狗和狗嘴: class Dog: Animal() { override var mouth
abstract class Animal {
var numberLegs: Int = 4
var mouth: Mouth? = null
}
abstract class Mouth {
abstract fun makeSound()
}
我现在可以创建狗和狗嘴:
class Dog: Animal() {
override var mouth: Mouth = DogMouth()
}
class DogMouth: Mouth() {
override fun makeSound() {
println("Bark!")
}
}
但这也允许我为狗指定其他类型的嘴,我不想要,例如:
class CatMouth: Mouth() {
override fun makeSound() {
println("Meow!")
}
}
fun main() {
val dog = Dog()
dog.mouth.makeSound() // will print "Bark!"
dog.mouth = CatMouth() // I don't want this to work
dog.mouth.makeSound() // will print "Meow!"
}
设置覆盖变量mouth:DogMouth=DogMouth()
不起作用
我如何确保狗只有狗嘴(和其他狗身体部位)?类似的问题得到解决和解决。 解决方案是使用通用参数:
abstract class Animal<MouthType: Mouth> {
var numberLegs: Int = 4
abstract var mouth: MouthType
}
class Dog: Animal<DogMouth>() {
override var mouth: DogMouth = DogMouth()
}
abstract class Animal<MouthType: Mouth, EarType: Ear, TailType: Tail> {
var numberLegs: Int = 4
abstract var mouth: MouthType
abstract var ear: EarType
abstract var tail: TailType
}