- Kotlin 教程
- Kotlin - 主页
- Kotlin - 概述
- Kotlin - 环境设置
- Kotlin - 架构
- Kotlin - 基本语法
- Kotlin - 评论
- Kotlin - 关键字
- Kotlin - 变量
- Kotlin - 数据类型
- Kotlin - 运算符
- Kotlin - 布尔值
- Kotlin - 字符串
- Kotlin - 数组
- Kotlin - 范围
- Kotlin - 函数
- Kotlin 控制流程
- Kotlin - 控制流
- Kotlin - if...Else 表达式
- Kotlin - When 表达式
- Kotlin - For 循环
- Kotlin - While 循环
- Kotlin - 中断并继续
- Kotlin 集合
- Kotlin - 集合
- Kotlin - 列表
- Kotlin - 集
- Kotlin - 地图
- Kotlin 对象和类
- Kotlin - 类和对象
- Kotlin - 构造函数
- Kotlin - 继承
- Kotlin - 抽象类
- Kotlin - 接口
- Kotlin - 可见性控制
- Kotlin - 扩展
- Kotlin - 数据类
- Kotlin - 密封类
- Kotlin - 泛型
- Kotlin - 委托
- Kotlin - 解构声明
- Kotlin - 异常处理
- Kotlin 有用资源
- Kotlin - 快速指南
- Kotlin - 有用的资源
- Kotlin - 讨论
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