ITPub博客

首页 > 应用开发 > Java > Scala多继承以及AOP

Scala多继承以及AOP

原创 Java 作者:541732025 时间:2015-11-24 10:17:40 0 删除 编辑

点击(此处)折叠或打开

  1. class Human{
  2.   println("Human")
  3. }

  4. trait TTeacher extends Human {
  5.   println("TTeacher")
  6.   def teach
  7. } 

  8. trait PianoPlayer extends Human {
  9.   println("PianoPlayer")
  10.   def playPiano = {println("I am playing piano. ")}
  11. } 

  12. class PianoTeacher extends Human with TTeacher with PianoPlayer { //构造PianoTeacher实例时,按照从左至右的顺序依次完成,仅构造一次
  13.     override def teach = {println("I am training students. ")}
  14. }

  15. object UseTrait extends App{
  16.    val t1 = new PianoTeacher
  17.    t1.playPiano
  18.    t1.teach
  19. }
结果:
Human
TTeacher
PianoPlayer
I am playing piano.
I am training students.

点击(此处)折叠或打开

  1. //AOP
  2. trait Action {
  3.     def doAction
  4. }

  5. trait TBeforeAfter extends Action {
  6.     abstract override def doAction {
  7.         println("Initialization")
  8.         super.doAction //因为调用了父类的抽象方法,所以本方法也是抽象的。super.doAction最终会在子类Work中实现,有点类似于模板方法设计模式。
  9.         println("Destroyed")
  10.     }
  11. }

  12. class Work extends Action{
  13.      override def doAction = println("Working...")
  14. }

  15. object UseTrait extends App{
  16.     val work = new Work with TBeforeAfter
  17.     work.doAction
  18. }
结果:
Initialization
Working...
Destroyed

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/28912557/viewspace-1845125/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: trait
请登录后发表评论 登录
全部评论

注册时间:2013-05-23

  • 博文量
    127
  • 访问量
    515720