当前位置:嗨网首页>书籍在线阅读

03-构造函数

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

5.1.2 构造函数

在Kotlin中,一个类主要由主构造函数和次构造函数组成,主构造函数是类头的一部分,它跟在类名或可选的类型参数后面。与Java定义构造函数的方式不同,Kotlin使用关键字constructor来定义构造函数。

class Example constructor(name: String) {
}

如果主构造函数没有任何注解,也没有任何限制性修饰符(public、private、protected和internal),则可以省略constructor关键字。

//省略constructor关键字
class Example(name : String){ … }
//有注解,不可以省略
class Example public @Inject constructor(name: String) { … }

在Kotlin的构造函数中,主构造函数不能包含任何的代码。主构造函数的参数既可以在init作为前缀的初始化代码块中调用,也可以在类中声明变量时调用。

class Example constructor(name: String) {
      //初始化成员变量
      var name : String = name
      //主构造函数初始化
      init {
           val customerKey = name.toUpperCase()
           }
}

事实上,对于属性声明以及主构造函数初始化属性,有一种简洁的写法。

class Example (val lastName: String, var age: Int) {
  //其他属性
}

次构造函数使用constructor关键字声明,当有主构造函数时,声明次构造函数需要使用this来关联。通过次构造函数实例化对象时会优先执行初始化块中的方法。

class Example constructor(name: String) {
    //主构造函数初始化
    init {
        println("name is:"+name)
    }
    //先调用初始化块中的方法,再执行本构造函数中的代码
    constructor(name: String, age: Int) : this(name) {
        println("age is:"+age.toString())
    }
}

这里先执行init中的代码,然后再执行次构造函数中的代码。

如果没有声明主、次构造函数,那么该类会有一个默认的没有参数的主构造函数,而且它是由public类型修饰的。如果不希望类有一个公有的构造函数,则只需要修改构造函数的可见性即可。

class Example private constructor () {
}