kotlin抽象类,接口,继承

接口:是一种约定.没有状态,专门用于别人继承. interface

抽象类:实现了一部分约定协议的半成品,可有状态,可有方法实现,也是专门用于别人继承,abstract class

抽象类只能单继承,接口可多继承

继承,父类需要open才能被子类继承,父类里面得方法,属性定义为open ,才能被override,复写父类的方法和属性必须加override

package com.testinterface

/**
 * Created by jingwen on 19/4/16.
 */
interface InputDevice {
    fun Input(device:Any)
}

interface UsbInputDevice:InputDevice
interface BleInputDevice:InputDevice

interface OpticalMouse
abstract class UsbMouse (var name:String):UsbInputDevice,OpticalMouse{
    override fun Input(device: Any) {
        println("UsbMouse input")
    }

    override fun toString(): String {
        return name
    }


}

class LogiMouse( name: String):UsbMouse(name){
    override fun Input(device: Any) {
        super.Input(device)
    }
}

class Computer{

    fun addUsbInputDevice(device:UsbInputDevice){
        println("add usb inputdevice $device")
    }

    fun addBleInputDevice(device:BleInputDevice){
        println("add ble inputdevice $device")
    }

    fun addInputDevice(device:InputDevice){
        println("add input device $device")
        when(device){
            is  UsbInputDevice -> {
                addUsbInputDevice(device)
            }
            is BleInputDevice ->{
                addBleInputDevice(device)
            }
            else -> {
                println("给我一个非输入设备")
            }
        }
    }
}

fun main(args: Array) {
    var computer:Computer = Computer()
    var mouse = LogiMouse("罗技鼠标")
    computer.addInputDevice(mouse)
}

输出结果:

add input device 罗技鼠标
add usb inputdevice 罗技鼠标

Process finished with exit code 0

 

你可能感兴趣的:(kotlin抽象类,接口,继承)