DEV Community

Stone
Stone

Posted on

kotlin learning notes Ⅳ—— interface

interface

The kotlin interface, similar to Java 8, uses the interface keyword to define the interface, allowing methods to have default implementations:

interface MyInterface {
    fun bar()    // not implemented
    fun foo() {  //implemented
      // Optional method body
      println("foo")
    }
}

implement interface

A class or object can implement one or more interfaces
example:

interface MyInterface {
    fun bar()
    fun foo() {
        // optional function
        println("foo")
    }
}
class Child : MyInterface {
    override fun bar() {
        println("bar")
    }
}

Properties in the interface

The attribute in the interface can only be abstract, and initialization value is not allowed. The interface will not save the property value. When implementing the interface, the property must be rewritten
(接口中的属性只能是抽象的,不允许初始化值,接口不会保存属性值,实现接口时,必须重写属性)
example:

interface MyInterface {
    var name:String //name , abstract
    fun bar()
    fun foo() {
        // 可选的方法体
        println("foo")
    }
}
class Child : MyInterface {
    override var name: String = "runoob" //override name
    override fun bar() {
        println("bar")
    }
}

override function

When implementing multiple interfaces, you may encounter the problem that the same method inherits multiple implementations. For example:

interface A {
    fun foo() { print("A") }   // implemented
    fun bar()                  // abstract, not implemented
}

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

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

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

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

fun main(args: Array<String>) {
    val d =  D()
    d.foo();
    d.bar();
}

output:

ABbar

Top comments (0)