如果一个类有多个父类,且父类的有相同的函数 f,在子类和父类中调用 super.f 都是按从右到左的调用函数的顺序。
这个规则名为:Linearization Rules

如下的代码

trait Base1 {
  def print() { println("Base1") }
}
trait A extends Base1 {
  override def print() { println("A"); super.print() }
}
trait B extends Base1 {
  override def print() { println("B"); super.print() }
}
class Base2 {
  def print() { println("Base2") }
}
trait Base3 {
  def print() { println("Base3") }
}
class C extends Base2 with Base3 with A with B {
  override def print() { println("C"); super.print() }
}
object Main extends App {
  (new C).print()
}

继承顺序为 C -> Base2, Base3, Base1, A, B,输出结果为:

C B A Base1

如果 class C 变成:

class C extends Base2 with A with Base3 with B {
  override def print() { println("C"); super.print() }
}

继承顺序为 C -> Base2, Base1, A, Base3, B,输出结果为:

C B Base3

相关文章:

  • 2022-12-23
  • 2021-11-19
  • 2021-05-19
  • 2021-11-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-10
猜你喜欢
  • 2021-04-25
  • 2021-12-16
  • 2021-12-19
  • 2021-07-17
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案