阅读量:2
在Kotlin中,接口实现多态与在Java中类似。你可以通过定义一个接口,然后创建多个实现该接口的类,每个类都有自己的实现。在运行时,可以根据需要选择合适的实现。这里有一个简单的例子来说明如何在Kotlin中实现接口多态:
- 首先,定义一个接口:
interface Animal {
fun makeSound(): String
}
- 然后,创建多个实现该接口的类:
class Dog : Animal {
override fun makeSound(): String {
return "Woof!"
}
}
class Cat : Animal {
override fun makeSound(): String {
return "Meow!"
}
}
- 接下来,创建一个函数,接受一个
Animal类型的参数,并调用其makeSound()方法:
fun playSound(animal: Animal) {
println(animal.makeSound())
}
- 最后,在主函数中,创建
Dog和Cat对象,并调用playSound()函数:
fun main() {
val dog = Dog()
val cat = Cat()
playSound(dog) // 输出 "Woof!"
playSound(cat) // 输出 "Meow!"
}
在这个例子中,playSound()函数接受一个Animal类型的参数,这使得它可以接受任何实现了Animal接口的类。这就是Kotlin中接口实现多态的方式。
以上就是关于“Kotlin接口怎样实现多态”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm