Kotlin 的构造函数分为主构造函数和次构造函数。
主构造函数是我们常用的构造函数。
每个类默认有一个不带参数的主构造函数。我们也可以显示的指明它的参数。
主构造函数没有函数体,直接定义在类名后面。
示例,
class Student1(val sno:String, val score:Int) : Person() {
}
这样,初始化的时候必须传入构造函数中的所有参数,如
val s1 = Student1("sno1", 66)
Person 类后面的空括号表示 Student 类的主构造函数在初始化的时候会调用 Person 类的无参构造函数。这个括号不能省略。
主构造函数没有函数体,如果想在主构造函数中添加一些逻辑,就用 init
结构体,这是 Kotlin 提供的。
class Student1(val sno:String, val score:Int) : Person() {
init {
println("Student1 init")
}
}
结合之前的例子,
不写构造函数的 Student 类,
package com.cosmos.helloworld
class Student : Person(){
var sno = ""
var score = 0
fun study(){
println("$sno is studying")
}
}
写构造函数的 Student1 类,
package com.cosmos.helloworld
class Student1(val sno:String, val score:Int) : Person() {
init {
println("Student1 init")
}
fun study(){
println("$sno is studying")
}
}
main() 函数调用验证,
package com.cosmos.helloworld
fun main(){
var s = Student()
s.sno = "no1"
s.score = 95
s.study()
s.name = "Tom"
s.id = 20216
s.work()
println("===============")
val s1 = Student1("no3", 99)
s1.study()
s1.id = 101
s1.name = "Gorden"
s1.work()
}
运行结果,
no1 is studying
Tom is working. He's id is 20216
===============
Student1 init
no3 is studying
Gorden is working. He's id is 101