1.抽象类与接口

抽象类(abstract)

abstract class A{
    fun getMyName(){
        println("A")
    }
}

接口(interface)

interface InputDevice {
    fun input(event: Any)
}

kotlin中接口可以继承接口

interface USBInputDevice: InputDevice

java8之前接口方法是不能有默认实现的,kotlin可以

interface BLEInputDevice: InputDevice{
    fun printName(){
        println("BLEInputDevice")
    }
}

kotlin中同样是单继承多实现

abstract class ThreeA{
    fun getMyName(){
        println("A")
    }
}
interface ThreeB{
    fun getName(){}
}
interface ThreeC{
    fun print(){}
}
class ThreeD :ThreeA(),ThreeB,ThreeC{

}

思考
如果继承的父类以及实现的接口具有相同的方法怎么办?

abstract class A{
    open fun x(): Int = 5
}

interface B{
    fun x(): Int = 1
}

interface C{
    fun x(): Int = 0
}

class D(var y: Int = 0): A(), B, C{

    override fun x(): Int {
        println("call x(): Int in D")
        if(y > 0){
            return y
        }else if(y < -200){
            return super.x()
        }else if(y < -100){
            return super.x()
        }else{
            return super.x()
        }
    }
}

你可能感兴趣的:(1.抽象类与接口)