Kotlin学习手册(三)接口

2019-10-30  本文已影响0人  Geekholt

如需转载请评论或简信,并注明出处,未经允许不得转载

Kotlin系列导读

Kotlin学习手册(一)类与继承
Kotlin学习手册(二)属性与字段
Kotlin学习手册(三)接口
Kotlin学习手册(四)内部类
Kotlin学习手册(五)函数
Kotlin学习手册(六)数组与集合
Kotlin学习手册(七)for循环
Kotlin学习手册(八)内联函数let、with、run、apply、also
Kotlin学习手册(九)空类型安全
Kotlin学习手册(十)带你真正理解什么是Kotlin协程

目录

接口定义

.java

public interface Fly {
    void start();
    boolean stop();
}

.kotlin

interface Fly {
    fun start()
    fun stop(): Boolean
}

接口实现

.java

public class Bird implements Fly {
    @Override
    public void start() {
        
    }

    @Override
    public boolean stop() {
        return false;
    }
}

.Kotlin

class Bird : Fly {
    override fun start() {

    }

    override fun stop(): Boolean {
        return false
    }
}

接口中的属性

你可以在接口中定义属性。在接口中声明的属性要么是抽象的,要么提供访问器的实现。在接口中声明的属性不能有field字段,因此接口中声明的访问器不能引用它们

interface Fly {
    val prop: speed // 抽象的

    val height: Int
        get() = 9999

    fun start() {
        print(speed)
    }
}

class Bird : Fly {
    override val speed: Int = 100
}

解决覆盖冲突

实现多个接口时,可能会遇到同一方法继承多个实现的问题

interface A {
    fun foo() { print("A") }
    fun bar()
}

interface B {
    fun foo() { print("B") }
    fun bar() { print("bar") }
}

class C : A, B {
    override fun foo() {
        super<A>.foo()
        super<B>.foo()
    }

    override fun bar() {
        super<B>.bar()
    }
}

如果我们从 A 和 B 派生 D,我们需要实现我们从多个接口继承的所有方法,并指明 D 应该如何实现它们

上一篇 下一篇

猜你喜欢

热点阅读