kotlin对象构造器

683 阅读1分钟

Java构造方法

当一个类需要根据不同的参数构造时,java可以创建多个构造方法:

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;' 
    }
}

缺陷:

  1. 如果需要支持任意参数组合,那么需要实现的构造方法会非常多
  2. 构造方法中的代码存在冗余,如两个方法对同一个字段进行操作

Kotlin默认构造方法

class Bird(val weight: Double = 0.00, val agr: Int = 0, val color: String = "blue")

构造方法中通过val或var声明的参数,自动成为对象的属性,且支持自由赋值:

val bird = Bird(1000.0, 2, "blue")
val bird = Bird(color = "black")

如果不按顺序给予参数,则应该指定参数名称。

init语句块

init语句块属于默认构造器的一部分,会在初始化时执行额外操作,构造方法的参数可以在init方法直接调用,也可以在语句块中初始化其他成语。多个init方法会按照从上到下的顺序进行执行。

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}.")
   }

}

从构造函数

可以有二级构造函数,需要加前缀 constructor,如果类有主构造函数,每个次构造函数都要,或直接或间接通过另一个次构造函数代理主构造函数。在同一个类中代理另一个构造函数使用 this 关键字:

class Person(val name: String) {

    constructor (name: String, age:Int) : this(name) {
        // 初始化...
    }
}

执行顺序:先执行委托的方法,再执行自身代码块的逻辑。

伴生对象工厂方法

依赖于kotlin提供的伴生对象,我们可以利用其来设计工厂方法,根据传入的不同参数,进行预处理,并调用不同的构造方法。

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(): String {
      return "$weight $age $color"
   }

}