kotlin-接口

kotlin-接口


主要内容

  • 接口特性
  • 实现
  • 属性
  • 重载函数
接口特性

与java 8 中的接口类似,接口允许方法有实现,和抽象类的区别是,接口中的属性不允许直接初始化,默认是 abstract的。

public interface SomeInterface{
    var value:String //默认abstract

    fun reading() // 未实现

    fun writing(){  //已实现
        // do nothing
    }
}

接口声明与类一致,猜测接口就是特殊的抽象类,接口可以继承类,java中是不允许接口继承类的。

open class Box constructor(var value:String){
    open var name:String = "jason"
}

interface IBox :Box{
    fun beat(){
        println("beat $name")
    }
}
接口实现

类或对象能实现一个或多个接口,接口也可以继承接口

interface IBox2 :IBox{
    override fun beat(){
        println("$name beat IBox2")
    }
}
接口定义属性

允许定义属性,不允许初始化值,接口不会保存属性值,实现接口时,必须重载属性:

interface MyInterface{
    var name:String //name属性
}

class MyImpl:MyInterface{
    override var name: String = "jason" //重载属性
}
重载函数

与类继承一致,当多个接口中存在相同函数时(同名,参数,返回值),需要分情况对待:

情况一:有一个接口实现了相同函数,子类不用再实现:

interface MyInterface{
    fun reading():String
}

interface MyAnotherInterface{

    fun reading():String {
        return "jason"
    };
}

/**不需要显示的重载接口中reading方法**/
class MyImpl:MyInterface,MyAnotherInterface{

}

情况二:相同函数接口中都未实现,官网文档中描述: so the compiler does not know which one to choose, and forces us to override foo() and say what we want explicitly .但是实际上,子类重载的函数中并不需要显示的指明调用接口的函数:

interface MyInterface{
    fun reading()
}

interface MyInterface2{
    fun reading()
}

class MyImpl:MyInterface,MyInterface2{
    override fun reading() {

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值