Kotlin
的接口可以既包含抽象方法的声明也包含实现。
- 使用关键字
interface
来定义接口。
- 一个类或者对象可以实现一个或者多个接口。
// 定义接口
interface InputDevice {
fun input(event: Any);
}
// 一个接口继承一个接口
interface USBInputDevice : InputDevice
interface BLEInputDevice : InputDevice
interface OpticalMouse
// 一个类实现多个接口
class USBMouse(var name:String):USBInputDevice,OpticalMouse {
override fun input(event: Any) {
}
override fun toString(): String {
return name;
}
}
class Computer {
fun addUSBInputDevice(inputDevice: USBInputDevice) {
println("add usb input device: $inputDevice");
}
fun addBLEInputDevice(inputDevice: BLEInputDevice) {
println("add BLE input device: $inputDevice");
}
fun addInputDevice(inputDevice: InputDevice) {
when (inputDevice) {
is USBInputDevice -> {
addUSBInputDevice(inputDevice)
}
is BLEInputDevice -> {
addBLEInputDevice(inputDevice)
}
else -> {
throw IllegalAccessException("输入设备类型不支持")
}
}
}
}
fun main() {
val computer = Computer();
val mouse = USBMouse("罗技的鼠标");
computer.addInputDevice(mouse);
}
接口中的属性
可以在接口中定义属性。在接口中声明的属性,要么是抽象的,要么提供访问器实现。在接口中声明的属性不能有幕后字段,因此接口中声明的访问器不能引用它们。
接口与抽象类的区别
- 抽象类有状态,接口没有状态(属性)
- 抽象类有方法实现,接口只能有无状态的默认实现
- 抽象类只能单继承,接口可以多实现
- 抽象类反应本质,接口体现能力
abstract class A {
var i = 0;
fun hello() {
println(i);
}
open fun hello1() {
println(i);
};
abstract fun hello2();
}
interface B {
var j: Int;
// 有默认实现
fun hello3() {
println(j);
}
fun hello4();
}
interface C;
class D(override var j: Int) : B {
// 需要重写
override fun hello4() {
}
}
class E : A() {
// 可以重写父类的方法
override fun hello1() {
}
// 有abstract,则必须重写与接口中的类似
override fun hello2() {
}
}
class F(override var j: Int) : A(), B, C {
override fun hello2() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun hello4() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
网友评论