Scala 中类的主构造函数与辅助构造函数使用示例

34 阅读1分钟

主构造函数 class Student()

辅助构造函数,提供更多的方式来创建对象

class Student(var name:String, val age:Int) {
  println("Student……")
  def this() = {
    this("未知",18) // 调用主构造函数
    println("辅助构造器被调用了…")
  }

  def this(age:Int) = {
    this("未知的", age)
  }

  def sayHi(): Unit = {
    println(s"我是$name,我今年$age")
  }
}

object class01 {
  def main(args: Array[String]): Unit = {
    // 创建对象:new 会自动调用主构造函数
    val stu1 = new Student("小花", 18)
    val stu2 = new Student()
    val stu3 = new Student(20)
    // 调用对象的方法
    stu1.sayHi()
    // 调用对象的方法
    stu3.sayHi()
  }
}
  • val 修饰的属性是只读的,不能被修改
  • Student() 构造函数(构造器),用来创建对象