Kotlin中的构造函数和继承
一.构造函数
1.1 主构造函数
Kotlin中构造函数分为主构造函数和次构造函数,主构造函数没有函数体,在声明类的同时声明:
class Phone(val osName: String, val phoneName: String) {
}
上面的*(val OsName: String)* 就是Phone类的主构造函数,由于主构造函数没有函数体,如果想要在主构造函数里实现一些逻辑时,可以通过init函数实现:
class Phone(val osName: String, val phoneName: String) {
init {
println("需要在主构造函数中实现的逻辑可以在init函数中实现")
}
}
ps:主构造函数中传入的参数可以直接作为该类的成员变量使用
1.2 次构造函数
Kotlin中,在类中实现的函数叫做次构造函数。在任何类中,主构造函数最多只能有一个,而次构造函数可以有很多个,但是当类中既有主构造函数又有次构造函数时,次构造函数都必须要调用主构造函数(直接或间接),比如:
class Phone(val osName: String, val phoneName: String) {
constructor(osName: String):this(osName, "DefaultPhoneName")
constructor():this("DefaultOsName")
}
Kotlin中也可以没有主构造函数,写法为:
class Phone {
constructor(osName: String, phoneName: String) {
}
}
二. 继承
Kotlin中对类,接口的实现均是采用 ":"符号,同Java一样,Kotlin中一个类可以继承一个类,多个接口。这里以View的继承实现为例,列举几种继承的实现方法:
2.1 主构造函数继承
即直接重写主构造函数:
class TestView(context: Context, attributeSet: AttributeSet? = null, defStyle: Int) :
View(context, attributeSet, defStyle) {
}
2.2 次构造函数继承
重写次构造函数:
class TestView : View {
constructor(context: Context, attributeSet: AttributeSet? = null, defStyle: Int) : super(
context,
attributeSet,
defStyle
)
constructor(context: Context, attributeSet: AttributeSet? = null) : super(context, attributeSet)
constructor(context: Context) : super(context)
}
2.3使用使用@JvmOverloads注解(类似2.1)
class TestView @JvmOverloads constructor(
context: Context,
attributeSet: AttributeSet? = null,
defStyle: Int = 0
) : View(context, attributeSet, defStyle) {
}
