动态绑定
    Scala 中属性和方法都是动态绑定,而 Java 中只有方法为动态绑定。

    1. // 定义一个父类
    2. class Person7() {
    3. var name: String = _
    4. var age: Int = _
    5. println("1. 父类的主构造器调用")
    6. def this(name: String, age: Int){
    7. this()
    8. println("2. 父类的辅助构造器调用")
    9. this.name = name
    10. this.age = age
    11. }
    12. def printInfo(): Unit = {
    13. println(s"Person: $name $age")
    14. }
    15. //可以多态
    16. def printInfo(person7: Person7): Unit = {
    17. println("Person: " + person7.printInfo())
    18. }
    19. }
    20. // 定义子类
    21. class Student7(name: String, age: Int) extends Person7(name, age) {
    22. var stdNo: String = _
    23. println("3. 子类的主构造器调用")
    24. def this(name: String, age: Int, stdNo: String){
    25. this(name, age)
    26. println("4. 子类的辅助构造器调用")
    27. this.stdNo = stdNo
    28. }
    29. override def printInfo(): Unit = {
    30. println(s"Student: $name $age $stdNo")
    31. }
    32. }
    33. class Teacher extends Person7 {
    34. override def printInfo(): Unit = {
    35. println(s"Teacher")
    36. }
    37. }

    调用

    1. val person = new Person7()
    2. val student = new Student7("abc", 11)
    3. val teacher = new Teacher()
    4. println("=======================")
    5. person.printInfo(student)
    6. /**
    7. 输出
    8. 1. 父类的主构造器调用
    9. 2. 父类的辅助构造器调用
    10. 3. 子类的主构造器调用
    11. 1. 父类的主构造器调用
    12. =======================
    13. Student: abc 11 null
    14. Person: ()
    15. */

    动态绑定

    1. val person = new Student7("abc", 11)
    2. println("=======================")
    3. person.printInfo()
    4. println(person.name)
    5. /**
    6. 1. 父类的主构造器调用
    7. 2. 父类的辅助构造器调用
    8. 3. 子类的主构造器调用
    9. =======================
    10. Student: abc 11 null
    11. */