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)

Hey ๐Ÿ˜

Want to help the DEV Community feel more like a community?

Head over to the Welcome Thread and greet some new community members!

It only takes a minute of your time, and goes a long way!