kotlin 构造函数重载
构造函数重载 (Constructor Overloading)
A Kotlin class has a primary constructor and one or more secondary constructors. When a class has more than one constructor, it will be known as constructor overloading.
Kotlin类具有一个主构造函数和一个或多个辅助构造函数。 当一个类具有多个构造函数时,将称为构造函数重载。
Kotlin中用于构造函数重载的程序 (Program for constructor overloading in Kotlin)
package com.includehelp
//declare Class with Parameterized primary constructor
class ConstructorOverloading(len:Int){
//Init block, executed when class is instantiated,
//before secondary constructor body execution
init {
println("Init Block : $len")
}
//Secondary Constructor,
//delegate primary constructor with 'this' keyword
constructor() : this(10) {
println("Secondary Constructor No Parameter")
}
//Parameterized Secondary Constructor,
//delegate primary constructor with 'this' keyword
constructor(name:String):this(name.length){
println("Secondary Constructor with One Parameter : $name")
}
//Parameterized Secondary Constructor with two parameter,
//call same class non Parameterized secondary constructor
//using 'this()'
constructor(a:Int, b:Int) : this() {
println("Secondary Constructor With Two Parameter [$a, $b]")
}
}
//Main Function, Entry Point of Program
fun main(args:Array<String>){
//Create instance of class , with Primary Constructor
ConstructorOverloading(100)
//Create instance of class,
//with no argument secondary constructor
ConstructorOverloading()
//Create instance of class,
//with one argument secondary constructor
ConstructorOverloading("India")
//Create instance of class,
//with two argument secondary constructor
ConstructorOverloading(10,20)
}
Output:
输出:
Init Block : 100
Init Block : 10
Secondary Constructor No Parameter
Init Block : 5
Secondary Constructor with One Parameter : India
Init Block : 10
Secondary Constructor No Parameter
Secondary Constructor With Two Parameter [10, 20]
翻译自: https://www.includehelp.com/kotlin/example-of-constructor-overloading.aspx
kotlin 构造函数重载