Kt学习笔记(七)接口、抽象类
一、接口
kt中的接口和Java中的接口类似,使用interface关键字声明,一个类可以实现多个借口,实现的方法和类继承相同,而且,接口中的属性和方法都是open的
/**
* 定义MyInterface接口
*/
interface MyInterface
{
fun process()
fun getName() : String
{
return "Bill"
}
}
/**
* MyClass类实现MyInterface接口, 重写方法
*/
class MyClass : MyInterface
{
override fun process() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getName(): String {
return super.getName()
}
}
在Kt中允许接口的方法包含默认的方法体,对于方法体的接口方法,并不要求一定重写这个方法。所以getName方法可以不重写。
二、抽象类
抽象类不能被实例化,需要使用abstract关键字声明,抽象类实现接口后,接口中没有函数体的函数可以不重写(override),接口中的这些方法就自动被继承到实现接口的抽象类中, 称为抽象方法。
open class Base
{
open fun f()
}
abstract class Derived : Base()
{
override abstract fun f()
}
抽象方法不需要使用open声明,因为抽象类本身就是可继承的
下一篇:
多线程情况下单元测试碰到的问题
