辅助构造函数;主构造函数

34 阅读1分钟

val 修饰的属性是只读的,不能被修改

Student() 称 class Student()

1. 主构造函数(构造器),用来创建对象

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

package level02
class Student(var name: String, val age: Int) {
  println("Student.........")

  // 辅助构造函数
  // 特点:1. 名字都是this 2. 第一行代码就是调用主构造器
  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 = {
    // 调用构造函数
    val stu1 = new Student("小花", 18)
    val stu2 = new Student()
    val stu3 = new Student(20)
    // 调用对象的方法
    stu1.sayHi()
    // 调用对象的方法
    stu2.sayHi()
    stu3.sayHi()
  }
}