Kotlin - 介面



本章我們將學習 Kotlin 中的介面。在 Kotlin 中,介面的工作方式與 Java 8 完全相同,這意味著它們既可以包含方法實現,也可以包含抽象方法宣告。類可以實現介面以使用其定義的功能。我們在第 6 章 - “匿名內部類”一節中已經介紹了一個介面示例。本章我們將對此進行更深入的學習。“interface”關鍵字用於在 Kotlin 中定義介面,如下面的程式碼片段所示。

interface ExampleInterface {
   var myVar: String     // abstract property
   fun absMethod()       // abstract method
   fun sayHello() = "Hello there" // method with default implementation
}

在上面的示例中,我們建立了一個名為“ExampleInterface”的介面,其中包含一些抽象屬性和方法。請注意名為“sayHello()”的函式,它是一個已實現的方法。

在下面的示例中,我們將把上面的介面實現到一個類中。

線上演示
interface ExampleInterface  {
   var myVar: Int            // abstract property
   fun absMethod():String    // abstract method
   
   fun hello() {
      println("Hello there, Welcome to TutorialsPoint.Com!")
   }
}
class InterfaceImp : ExampleInterface {
   override var myVar: Int = 25
   override fun absMethod() = "Happy Learning "
}
fun main(args: Array<String>) {
   val obj = InterfaceImp()
   println("My Variable Value is = ${obj.myVar}")
   print("Calling hello(): ")
   obj.hello()
   
   print("Message from the Website-- ")
   println(obj.absMethod())
}

上面的程式碼將在瀏覽器中產生以下輸出。

My Variable Value is = 25
Calling hello(): Hello there, Welcome to TutorialsPoint.Com!
Message from the Website-- Happy Learning 

如前所述,Kotlin 不支援多重繼承,但是可以透過同時實現多個介面來實現相同的效果。

在下面的示例中,我們將建立兩個介面,然後將這兩個介面實現到一個類中。

線上演示
interface A {
   fun printMe() {
      println(" method of interface A")
   }
}
interface B  {
   fun printMeToo() {
      println("I am another Method from interface B")
   }
}

// implements two interfaces A and B
class multipleInterfaceExample: A, B

fun main(args: Array<String>) {
   val obj = multipleInterfaceExample()
   obj.printMe()
   obj.printMeToo()
}

在上面的示例中,我們建立了兩個示例介面 A 和 B,並在名為“multipleInterfaceExample”的類中實現了前面宣告的兩個介面。上面的程式碼將在瀏覽器中產生以下輸出。

method of interface A
I am another Method from interface B
廣告