- Kotlin的接口与Java8类似,既包含抽象方法的声明也包含实现。
- Kotlin的接口与抽象类不同的是,接口无法保存状态,接口可以有属性但必须声明为抽象或提供访问器实现。
接口定义
- Kotlin的接口使用关键字
interface
来定义
//接口使用interface关键字定义
interface InterfaceName{
//未实现的方法
fun fn()
//已实现的方法,方法体是可选的。
fun func(){
println("hello world")
}
}
接口实现
//接口使用interface关键字定义
interface InterfaceName{
//未实现的方法
fun fn()
//已实现的方法,方法体是可选的。
fun func(){
println("hello world")
}
}
class ClassName:InterfaceName{
override fun fn(){
println("override function fn")
}
override fun func(){
println("override function func")
}
}
fun main(args:Array<String>) {
val obj = ClassName()
obj.fn()
obj.func()
}
接口属性
- 可以在接口中定义属性,在接口中声明的属性要么是抽象的,要么提供访问器的实现。
- 在接口中声明的属性不能有幕后字段(backing field),因此接口中声明的访问器不能引用它们。
//接口使用interface关键字定义
interface InterfaceName{
//抽象的接口属性
val prop:Int
//提供访问器实现的接口属性
val propWithImpl:String
get() = "property with implement"
//未实现的方法
fun fn()
//已实现的方法,方法体是可选的。
fun func(){
println("hello world")
}
}
class ClassName:InterfaceName{
override val prop:Int = 0
override fun fn(){
println("override function fn")
}
override fun func(){
println("override function func")
}
}
fun main(args:Array<String>) {
val obj = ClassName()
obj.fn()//override function fn
obj.func()//override function func
println(obj.prop)//0
println(obj.propWithImpl)//property with implement
}
接口继承
- 接口可以从其他接口派生,既提供基类成员的实现也声明新的函数与属性。
//接口使用interface关键字定义
interface InterfaceBase{
//抽象的接口属性
val prop:Int
//提供访问器实现的接口属性
val propWithImpl:String
get() = "property with implement"
//未实现的方法
fun fn()
//已实现的方法,方法体是可选的。
fun func(){
println("base interface function func")
}
}
//接口继承
interface InterfaceChild:InterfaceBase{
val id:Int
val name:String
override val prop:Int get() = id
}
data class ClassName(
override val id:Int,
override val name:String,
val nick:String
):InterfaceChild{
override fun fn(){
println("override function fn")
}
}
fun main(args:Array<String>) {
val obj = ClassName(1, "junchow","jc")
println(obj.id)//1
println(obj.name)//junchow
println(obj.nick)//jc
obj.fn()//override function fn
obj.func()//base interface function func
}