从0到1学习 Kotlin 之—— kotlin 接口

xiaoxiao2021-02-28  32

接口

Kotlin 中的接口和Java8中的很相似,既有抽象方法,又可以有实现。和抽象类不同的是,接口不能保存状态。可以有属性但必须是抽象的,或者提供访问器的实现。

接口用关键字 interface 来定义:

interface Mother { fun color() fun size() { //函数体是可选的 } }

接口的实现

一个类或对象可以实现一个或多个接口

class Jack:Mother{ fun color(){ //函数体是可选的 } fun size() { //函数体是可选的 } }

接口中的属性

可以在接口中申明属性。接口中的属性要么是抽象的,要么提供访问器的实现。接口属性不可以有后备字段。而且访问器不可以引用它们。

interface Father { val size: Int // abstract val color: String get() = "red" fun take() { print("size id $size color is $color.get()") } } class Turner :Father { override val size: Int = 29 }

解决重写冲突

当我们在父类中声明了许多类型,有可能出现一个方法的多种实现。比如:

interface Mother { fun color() { print("red") } fun size() } interface Father { fun color() { print("blue") } fun size() { print("180") } } class Jones : Mother { override fun color() { print("red") } } class Cotton : Mother, Father { override fun color() { super<Mother>.color() super<Father>.color() } } Mother  Father 接口都有声明了 color() size() 函数。它们都实现了 color() 方法,但只有 Father 实现了 size() , size() 在 Mother 中并没有实现 它是抽象的,这是因为在接口中如果函数没有函数体,那么默认是抽象的。现在,如果我们从 Mother 中派生一个 Jones  实体类,显然我们需要重写 size() ,并实现它。而我们从 Mother 和 Father 派生一个 Cotton ,我们不用重写 size() 方法,因为我们的一个继承中有一个已经实现了它。但我们继承了两个 color() 的实现,因此编译器不知道应该选哪个,并强制我们重写 color() 并且明确指出我们具体想怎么实现,自己来重写。

参考:http://www.kotlindoc.cn/ClassesAndObjects/Interfaces.html

转载请注明原文地址: https://www.6miu.com/read-1750068.html

最新回复(0)