Kotlin learning: Kotlin interface

Kotlin interface

The Kotlin interface is similar to Java 8. The interface keyword is used to define the interface, allowing the method to have a default implementation

interface MyInterface {
    fun bar()    // 未实现
    fun foo() {  //已实现
      // 可选的方法体
      println("foo")
    }
}

Implement the interface

A class or object can implement one or more interfaces

class Child : MyInterface {
    override fun bar() {
        // 方法体
    }
}

Instance

interface MyInterface {
    fun bar()
    fun foo() {
        // 可选的方法体
        println("foo")
    }
}
class Child : MyInterface {
    override fun bar() {
        // 方法体
        println("bar")
    }
}
fun main(args: Array<String>) {
    val c =  Child()
    c.foo();
    c.bar();
 
}

Output result

foo
bar

Attributes in the interface

The attributes in the interface can only be abstract, and initialization values ​​are not allowed. The interface will not save the attribute value. When implementing the interface, the attribute must be rewritten.

interface MyInterface{
    var name:String //name 属性, 抽象的
}
 
class MyImpl:MyInterface{
    override var name: String = "runoob" //重写属性
}

Instance

interface MyInterface {
    var name:String //name 属性, 抽象的
    fun bar()
    fun foo() {
        // 可选的方法体
        println("foo")
    }
}
class Child : MyInterface {
    override var name: String = "runoob" //重写属性
    override fun bar() {
        // 方法体
        println("bar")
    }
}
fun main(args: Array<String>) {
    val c =  Child()
    c.foo();
    c.bar();
    println(c.name)
 
}

Output result

foo
bar
runoob

Function rewriting

When implementing multiple interfaces, you may encounter the problem of inheriting multiple implementations of the same method. E.g

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 {
    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();
}

The output result is

ABbar

In the example, interfaces A and B both define methods foo() and bar(), both of which implement foo(), and B implements bar(). Because C is a concrete class that implements A, it is necessary to rewrite bar() and implement this abstract method.

However, if we derive D from A and B, we need to implement all the methods inherited by multiple interfaces and specify how D should implement them. This rule applies to both methods that inherit from a single implementation (bar()) and methods that inherit from multiple implementations (foo())

Guess you like

Origin blog.csdn.net/PrisonJoker/article/details/113749486