Google力荐的现代语言Kotlin——学完你就会喜欢

Kotlin:接口能包含属性和方法实现了

2017-09-13  本文已影响53人  1024工场

一、接口定义


  1. Kotlin的接口与Java 8类似,即包含抽象方法的声明,也包含实现
  2. 与抽象类不同的是,接口无法保存状态可以有属性必须声明或提供访问器实现;
  3. 使用关键字interface来定义
//3.使用关键字interface定义接口MyInterface
interface MyInterface {
    fun bar()
    //1.可以包含方法foo()实现
    fun foo() {
     
    }
}

二、实现接口


  1. 一个类或对象可以实现一个或多个接口
//1.Child类实现了MyInterface接口,实现bar()方法
class Child : MyInterface {
    override fun bar() {
        // 方法体
    }
}

三、接口中属性


  1. 可以在接口中定义属性,要么是抽象的,要么提供访问器的实现
  2. 接口中声明的属性不能有幕后字段,因此接口声明的访问器不能引用它们;
interface MyInterface {
    //1.声明抽象的属性prop
    val prop: Int 

    val propertyWithImplementation: String
        get() = "foo"

    fun foo() {
        print(prop)
    }
}

class Child : MyInterface {
    //1.覆盖属性prop
    override val prop: Int = 29
}

四、解决覆盖冲突


  1. 实现多个接口时,可能会遇到同一个方法继承多个实现的情况,通过类型限定的super关键字指定实现
interface A {
    fun foo() { print("A") }
    fun bar()
}

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

class C : A {
    override fun bar() { print("bar") }
}

class D : A, B {
    //D分别从A、B接口继承foo()方法
    override fun foo() {
        //1.使用super关键字,调用A和B foo()方法实现
        super<A>.foo()
        super<B>.foo()
    }

    override fun bar() {
        //1.实现super关键字,调用B bar()方法实现
        super<B>.bar()
    }
}

1.新技术,新未来!尽在1024工场。时刻关注最前沿技术资讯,发布最棒技术博文!(甭客气!尽情的扫描或者长按!)

1024工场服务号
2.加入“Kotlin开发”QQ讨论群,一起学习一起Hi。(甭客气!尽情的扫描或者长按!)
Kotlin开发群
上一篇下一篇

猜你喜欢

热点阅读