主副构造器

23 阅读1分钟

构造函数

1.主构造器

2.辅助构造器

特点:

1.名字就叫做this。它的代码的第一行必须是调用主构造器。可以有多个

2.提供更多的创建对象的方式

object class01 {
  //calss 类

  //Student为构造函数。原来创建对象。new 的时候。就会自动调用一次构造函数
  class Student(var name:String, var age:Int) {
    println("Student构造函数被调用.....")

    // 辅助构造函数1
    def this(name:String){
      this(name,15)
    }
    // 辅助构造函数2
    def this(age:Int){
      this("未知",age)
      println("Student构造函数被调用.....")
    }


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

  }
  def main(args: Array[String]): Unit = {
    //实例化类的对象 stu
    //new 的时候。就会自动调用一次构造函数
    val stu = new Student("小花",18)

    //调用对象的方法
    stu.sayHello()

    val stu1 = new Student("小明")//调用辅助构造器1
    stu1.sayHello()

    val stu2 = new Student(20)//调用辅助构造器2
    stu1.sayHello()
  }
}