前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[Kotlin] 构造函数总结

[Kotlin] 构造函数总结

原创
作者头像
用户3702315
修改2021-03-30 14:26:00
1.1K0
修改2021-03-30 14:26:00
举报
文章被收录于专栏:安卓开发安卓开发
主构造函数
代码语言:txt
复制
// Kotlin 的构造函数可以写在类头中,跟在类名后面。
// 这种写法声明的构造函数,我们称之为主构造函数。
class Person(private val name: String) {
    fun sayHello() {
        // 主构造函数中声明的参数,它们默认属于类的公有字段。
        println("hello $name")
    }
}
// 与上面的作用一致:声明主构造函数
class Person constructor(private val name: String) {
    fun sayHello() {
        println("hello $name")
    }
}
/// 与上面的作用一致,修饰符默认是:public
class Person public constructor(private val name: String) {
    fun sayHello() {
        println("hello $name")
    }
}

// 如果有注解是在主构造函数上,必须带上关键字:constructor
class Person  @TargetApi(28) constructor(private val name: String) {
    fun sayHello() {
        println("hello $name")
    }
}

// 如果有额外的代码需要在构造方法中执行,需要放到 init 代码块中执行
class Person(private var name: String) {

    init {
        name = "Hello World"
    }

    internal fun sayHello() {
        println("hello $name")
    }
}
次级构造函数
代码语言:txt
复制
class Person(private var name: String) {

    private var description: String? = null

    init {
        name = "Hello World"
    }

    // 如有主构造函数,则要继承主构造函数
    constructor(name: String, description: String) : this(name) {
        this.description = description
    }

    internal fun sayHello() {
        println("hello $name")
    }
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 主构造函数
  • 次级构造函数
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档