Scala辅助构造器

洛茄

关注

阅读 54

2022-01-24

// 演示辅助构造器
object 演示辅助构造器 {

  class Customer(val name: String, val address: String) {
    def this(arr: Array[String]) {
      // 注意:辅助构造器的第一行代码必须访问主构造器或者其他的辅助构造器
      this(arr(0), arr(1))
    }
  }

  def main(args: Array[String]): Unit = {
    // 通过辅助构造器创建Customer对象
    val c = new Customer(Array("张三", "北京"))
    println(c.name, c.address)

    // 通过主构造器创建Customer对象
    val c2 = new Customer("李四", "上海")
    println(c2.name, c2.address)
  }

}

精彩评论(0)

0 0 举报