温馨提示×

Kotlin接口怎样实现多态

小樊
101
2024-11-03 07:31:52
栏目: 编程语言

在Kotlin中,接口实现多态与在Java中类似。你可以通过定义一个接口,然后创建多个实现该接口的类,每个类都有自己的实现。在运行时,可以根据需要选择合适的实现。这里有一个简单的例子来说明如何在Kotlin中实现接口多态:

  1. 首先,定义一个接口:
interface Animal { fun makeSound(): String } 
  1. 然后,创建多个实现该接口的类:
class Dog : Animal { override fun makeSound(): String { return "Woof!" } } class Cat : Animal { override fun makeSound(): String { return "Meow!" } } 
  1. 接下来,创建一个函数,接受一个Animal类型的参数,并调用其makeSound()方法:
fun playSound(animal: Animal) { println(animal.makeSound()) } 
  1. 最后,在主函数中,创建DogCat对象,并调用playSound()函数:
fun main() { val dog = Dog() val cat = Cat() playSound(dog) // 输出 "Woof!" playSound(cat) // 输出 "Meow!" } 

在这个例子中,playSound()函数接受一个Animal类型的参数,这使得它可以接受任何实现了Animal接口的类。这就是Kotlin中接口实现多态的方式。

0