一、类声明
由类名和类头(参数、主构造函数等)及大括号组成,类头和大括号都可以省略
1
2
3
class Person { /*...*/ }
class Empty
默认会生成一个公开的无参构造函数,如果你不希望有公开的构造函数
1
class DontCreateMe private constructor() { /*...*/ }
二、 构造函数
主构造函数直接在类头中进行声明
1
2
3
4
5
6
7
class Person constructor(firstName: String) { /*...*/ }
//没有注释或修饰符时 可省略 constructor
class Person(firstName: String) { /*...*/ }
//如 使用依赖注入时,对此构造添加了注入注释时则不可省略constructor
class Person @Inject constructor(firstName: String) { /*...*/ }
类头不可以包含可运行代码,如果要在对象创建期间运行某些代码,可以在类的初始化代码块init
中执行,在初始化期间会按照类中定义init 或 属性的顺序执行
1
2
3
4
5
6
7
8
9
10
11
12
13
class InitOrderDemo(name: String) {
val firstProperty = "First property: $name".also(::println)
init {
println("First initializer block that prints $name")
}
val secondProperty = "Second property: ${name.length}".also(::println)
init {
println("Second initializer block that prints ${name.length}")
}
}
主函数中的参数可在初始化块中直接使用
1
2
3
class Customer(name: String) {
val customerKey = name.uppercase()
}
可以直接在构造函数中声明定义属性并赋予默认值
1
2
3
4
5
class Person(
val firstName: String,
val lastName: String,
var isEmployed: Boolean = true
){}
声明二级构造函数,当类具有主构造函数时,所有的二级构造函数都需要使用this
关键字间接的委托给主构造函数
1
2
3
4
5
6
class Person(val name: String) {
val children: MutableList<Person> = mutableListOf()
constructor(name: String, parent: Person) : this(name) {
parent.children.add(this)
}
}
需要注意
init
初始化代码块是主构造函数的一部分,所以会优先于二级构造函数执行.
三、 类创建
与java不同,不需要new关键字
1
2
3
val invoice = Invoice()
val customer = Customer("Joe Smith")