一、构造器

object ConstructorApp {
  def main(args: Array[String]): Unit = {

    // 传两个参数,对应到主构造器
    val person = new Person("zhansan", 32)
    println(person.name + ":" + person.age + ":" + person.school)

    // 传三位参数,对应到附属构造器
    val person2 = new Person("zhansi", 18, "M")
    println(person2.name + ":" + person2.age + ":" + person2.school + ":" + person2.gender)

  }
}


// 跟在类名后面的称为“主构造器”
class Person(val name: String, val age: Int) {
  println("Person Constructor enter...")

  val school         = "ustc"
  var gender: String = _

  // 附属构造器,把主构造器的参数直接拿来用
  def this(name: String, age: Int, gender: String) {
    this(name, age) // 附属构造器的第一行,必须调用主构造器,或者其它附属构造器
    this.gender = gender

  }

  println("Person Constructor leave...")
}

运行结果可以看到先执行了主构造器,再执行附属构造器

Person Constructor enter...
Person Constructor leave...
zhansan:32:ustc

Person Constructor enter...
Person Constructor leave...
zhansi:18:ustc:M

二、继承

使用extend 继承父类

// Student 继承了Person,如果我们要使用Person的属性,Student构造器的参数不需要加 val 或var,否则要加上
class Student(name:String, age:Int, var major:String) extends Person(name, age){
  println("Student Constructor enter...")

  println("Student Constructor leave...")
}

调用student

val student = new Student("zhangwu", 16, "Math")
println(student.name + ":" + student.major)
println(student)

输出结果:先执行父类主构造器,再执行Student的构造器

Person Constructor enter...
Person Constructor leave...

Student Constructor enter...
Student Constructor leave...
zhangwu:Math

com.hhcycj.scala.object_04.Student@39aeed2f

println(student) 相当于 println(student.toString)

三、重写

通过 override 关键字,重写 ObjecttoString 方法

override def toString: String = "override def toString"

重写父类的 school 属性

 override val school: String = "li yang xiao xue"