Kotlin學習筆記系列:http://blog.csdn.net/column/details/16696.html
interface FlyAnimal{
val wings : Wings
fun fly() = wings.move()
}
class Bird : FlyAnimal{
override val wings : Wings = Wings()
}
可以看到在接口中實現了函數,所以子類不必再重寫,但是屬性沒有實現,子類需要去實現屬性。interface CanFly{
fun fly()
}
class AnimalWithWings : CanFly{
val wings : Wings = Wings()
override fun fly() = wings.move()
}
class Bird(f : CanFly) : CanFly by f
//使用時
val bird = Bird(AnimalWithWings())
bird.fly()
我們定義了一個接口CanFly,AnimalWithWings實現了這個接口,Bird也實現了這個接口但是委託了AnimalWithWings,所以Bird不用去實現接口了。class Bat : CanFly by AnimalWithWings()
//使用時
val bat = Bat()
bat.fly()