super并不是指继承关系,而是指的加载顺序,从右到左,不一定调用父类的,而是调用左边的混入特质,左边没有了,才调用父类的
继承多个相同父特质的类,会从右到左依次调用特质的方法。Super指的是继承特质左边的特质,从源码是无法判断super.method会执行哪里的方法,如果想要调用具体特质的方法,可以指定:super[ConsoleLogger].log(…).其中的泛型必须是该特质的直接超类类型
trait Logger4 {
def log(msg: String);
}
trait ConsoleLogger4 extends Logger4 {
def log(msg: String) {
println(msg)
}
}
trait TimestampLogger4 extends ConsoleLogger4 {
override def log(msg: String) {
super.log(new java.util.Date() + " " + msg)
}
}
trait ShortLogger4 extends ConsoleLogger4 {
override def log(msg: String) {
super.log(if (msg.length <= 15) msg else s"${msg.substring(0, 12)}...aaaa")
}
}
class Account4 {
protected var balance = 0.0
}
abstract class SavingsAccount4 extends Account4 with Logger4 {
def withdraw(amount: Double) {
if (amount > balance) log("余额不足")
else balance -= amount
}
}
object Main4 extends App {
//super 特质 从右到左 ShortLogger4 -> TimestampLogger4
val acct1 = new SavingsAccount4 with TimestampLogger4 with ShortLogger4
//TimestampLogger4 -> ShortLogger4
val acct2 = new SavingsAccount4 with ShortLogger4 with TimestampLogger4
acct1.withdraw(100)
acct2.withdraw(100)
}
尖叫提示:抽象类混入特质,从右往左调用,super调用的是当前特质左边的特质,如果没有特质了,才调用父类的,而不是直接调用父类的方法,如果想直接调用父类的,可以加泛型限制