kotlin中主构函数可以显示用construct在类名后声明,也可以省略。次构函数的语法是“:this(上一级构造函数参数)”。实例化后即可自动执行主构函数和次构函数中的代码。 例子:
class Stdent(val name: String,val age:Int){
init {
println("我的名字叫:${name},我的年龄是:${age}")
}
constructor(name: String,age: Int,height: Float) :this(name,age){
println("我的名字叫:${name},我的年龄是:${age},我的身高是${height}")
}
constructor(name: String,age: Int,height: Float,sex: String) :this(name,age,height){
println("我的名字叫:${name},我的年龄是:${age},我的身高是${height},我的性别是${sex}")
}
}
fun main(){
var p = Stdent("小明",15,156.3f, sex = "男")
}