Java constructors
When a class needs to be constructed from different parameters, Java can create multiple constructors:
class Bird{
private double weight;
private int age;
private String color;
public Bird(double weight, int age, String color){
this.weight = weight;
this.age = age;
this.color = color;
}
public Bird(double weight){
this.weight = weight;'}}Copy the code
Defect:
- If you need to support any combination of parameters, the number of constructors you need to implement is very large
- There is redundancy in the constructor code, such as two methods operating on the same field
Kotlin default constructor
class Bird(val weight: Double = 0.00.val agr: Int = 0.val color: String = "blue")
Copy the code
Constructor parameters declared by val or var automatically become attributes of the object and support free assignment:
val bird = Bird(1000.0.2."blue")
val bird = Bird(color = "black")
Copy the code
If the parameters are not given in order, the parameter name should be specified.
Init blocks
The init statement block is part of the default constructor and performs additional operations on initialization. Constructor arguments can be called directly in the init method or other idioms can be initialized in the statement block. Multiple init methods are executed from top to bottom.
class Bird(weight: Double, age: Int, color: String) {
val weight: Double
val age: Int
val color: String
init {
this.weight = weight
println("The bird's weight is ${this.weight}.")
this.age = age
println("The bird's age is ${this.age}.")}init {
this.color = color
println("The bird's color is ${this.color}.")}}Copy the code
From the constructor
You can have secondary constructors, which need to be prefixed by constructor. If a class has a primary constructor, each secondary constructor needs to, either directly or indirectly, proxy the primary constructor through another secondary constructor. Proiding another constructor in the same class using the this keyword:
class Person(val name: String) {
constructor (name: String, age:Int) : this(name) {
// Initialize...}}Copy the code
Execution order: Execute the delegate method first, then execute the logic of its own code block.
Associated object factory method
Depending on the companion object provided by Kotlin, we can use it to design factory methods, preprocess them, and call different constructors based on the different parameters passed in.
class Cat(val weight: Double = 0.00.val age: Int = 0.val color: String = "blue") {companion object{
fun create(
createType:Int
):Cat {
return when (createType) {
1 -> Cat(weight = 1.0)
2 -> Cat(age = 1)
3 -> Cat(color = "black")
else -> Cat()
}
}
}
override fun toString(a): String {
return "$weight $age $color"}}Copy the code