失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Kotlin笔记9--无参构造函数

Kotlin笔记9--无参构造函数

时间:2020-11-01 03:11:07

相关推荐

Kotlin笔记9--无参构造函数

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.helloworldclass Student : Person(){var sno = ""var score = 0fun study(){println("$sno is studying")}}

写构造函数的 Student1 类,

package com.cosmos.helloworldclass Student1(val sno:String, val score:Int) : Person() {init {println("Student1 init")}fun study(){println("$sno is studying")}}

main() 函数调用验证,

package com.cosmos.helloworldfun main(){var s = Student()s.sno = "no1"s.score = 95s.study()s.name = "Tom"s.id = 6s.work()println("===============")val s1 = Student1("no3", 99)s1.study()s1.id = 101s1.name = "Gorden"s1.work()}

运行结果,

no1 is studyingTom is working. He's id is 6===============Student1 initno3 is studyingGorden is working. He's id is 101

如果觉得《Kotlin笔记9--无参构造函数》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。