面试题答案
一键面试- 主构造函数:
- 当子类继承父类且有主构造函数时,父类的构造函数必须在子类主构造函数的参数列表后立即调用。
- 示例:
open class ParentClass(val name: String) {
init {
println("ParentClass initialized with name: $name")
}
}
class ChildClass(name: String, val age: Int) : ParentClass(name) {
init {
println("ChildClass initialized with age: $age")
}
}
在上述例子中,ChildClass
继承自 ParentClass
。ChildClass
的主构造函数接受两个参数 name
和 age
,其中 name
用于调用父类 ParentClass
的主构造函数。
- 次构造函数:
- 如果子类没有主构造函数,那么每个次构造函数必须通过
this
关键字委托给同一个类的另一个构造函数,最终委托给父类的构造函数。 - 示例:
- 如果子类没有主构造函数,那么每个次构造函数必须通过
open class BaseClass(val value: Int) {
init {
println("BaseClass initialized with value: $value")
}
}
class SubClass : BaseClass {
constructor(value: Int, message: String) : this(value) {
println("SubClass constructor with message: $message")
}
constructor(value: Int) : super(value) {
println("SubClass basic constructor")
}
}
在这个例子中,SubClass
没有主构造函数。它有两个次构造函数,其中一个构造函数 constructor(value: Int, message: String)
通过 this(value)
委托给另一个构造函数 constructor(value: Int)
,而这个构造函数再通过 super(value)
调用父类 BaseClass
的构造函数。