在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中接口实现多态的方式。