Kotlin 接口
在本章中,我们将了解 Kotlin 中的接口。在 Kotlin 中,接口的工作方式与 Java 8 完全相似,这意味着它们可以包含方法实现以及抽象方法声明。接口可以由类实现以使用其定义的功能。我们已经在第 6 章“匿名内部类”一节中介绍了一个带有接口的示例。在本章中,我们将了解更多相关信息。关键字“interface”用于在 Kotlin 中定义接口,如下面的代码所示。
interface 例子Interface { var myVar: String // 抽象属性 fun absMethod() // 抽象方法 fun sayHello() = "Hello there" // 默认实现的方法 }
在上面的例子中,我们创建了一个名为“例子Interface”的接口,在里面我们有几个抽象的属性和方法。看看名为“sayHello()”的函数,这是一个实现的方法。
在下面的例子中,我们将在一个类中实现上述接口。
interface 例子Interface { var myVar: Int // 抽象属性 fun absMethod():String // 抽象方法 fun hello() { println("Hello there, Welcome to Newbiego.com!") } } class InterfaceImp : 例子Interface { 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 Newbiego.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") } } // 实现两个接口A和B class multipleInterface例子: A, B fun main(args: Array<String>) { val obj = multipleInterface例子() obj.printMe() obj.printMeToo() }
在上面的示例中,我们创建了两个示例接口 A、B,并在名为“multipleInterface例子”的类中实现了两个之前声明的接口。上面的代码将在浏览器中产生以下输出。
method of interface A I am another Method from interface B