trait Action {
def doAction
}
trait TBeforeAfter extends Action {
abstract override def doAction {
println("Initialization")
super.doAction
println("Destroyed")
}
}
class Work extends Action{
override def doAction = println("Working...")
}
object UseTrait extends App{
val work = new Work with TBeforeAfter
work.doAction
}
输出:
Initialization
Working...
Destroyed
解释:
work.doAction会调用TBeforeAfter的doAction方法,所以会打印Initialization和Destroyed,中间的Working是super.doAction调用了父类Action的doAction方法,该方法是抽象方法,所以会寻找子类中的实现,找到了Work类中的doAction方法。
时间: 2024-10-07 05:15:44