目录
构造函数类型
- 主构造函数(主构造器)------只能有一个
- 次构造函数(次构造器)------可以是多个
主构造函数
构造器 constructor关键字前 无注解或修饰符作用,可直接省略
class Singleton private constructor (age:Int){} class Singleton (age:Int){}
成员变量设置
//在构造器直接初始化(用var/val修饰变量)
class Singleton private constructor (var age:Int = 20){
// 在构造器声明,在类内部初始化
class Singleton private constructor (age:Int = 20){ private val age:Int = age
//在构造器声明,在init初始化程序块 初始化
class Singleton private constructor (age:Int = 20){ private val age:Int init { this.age = age }
私有化操作
使外部无法通过主构造创建对象
class Singleton private constructor (var age:Int = 20){}
次级构造函数
目的:为类的构造提供多种结构,更灵活
语法规则:
- constuctor关键字不能省略
- 次级构造函数会直接或间接调用主构造函数
class Singleton private constructor ( age:Int ){ constructor(name:String,age:Int) : this(age) { } constructor(sex:Char,name: String,age: Int) : this(name,age) { }
- 次构造函数调用()
fun main(){ val sg1:Singleton = Singleton("zhoujun",3) val sg2:Singleton = Singleton('m',"zhoujun",3) }
- 次级构造函数调用父类次级构造
open class Person { constructor(name:String,age:Int){ } constructor(name: String,age: Int,sex:String):this(name,age){ } } class Man: Person{ constructor(name:String,age: Int):super(name,age){ } constructor(name:String,age: Int,sex: String):super(name,age, sex){ } }
- 伴生类实现单例模式(具体参考http://t.csdnimg.cn/tV3OH)
class BAT private constructor(){ companion object{ //单例对象创建 } }