Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 有没有办法用声明类型的子类型重写抽象属性?_Kotlin_Polymorphism_Abstract Class - Fatal编程技术网

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
}