package kmust.hjr.learningScala15
/**
* Created by Administrator on 2015/7/20.
*/
class Human{
println("Human")
}
trait TTeacher extends Human{
println("TTeacher")
def teach
}
trait PianoPlayer extends Human{
println("PianoPlayer")
def playPiano={println("I'm playing piano.")}
}
class PianoTeacher extends Human with TTeacher with PianoPlayer{
override def teach={println("I'm training students. ")}
}
实例一
object UseTrait {
def main(args:Array[String]): Unit ={
val t1=new PianoTeacher
t1.playPiano
t1.teach
}
}
![这里写图片描述](https://img-blog.csdn.net/20150720235344652)
**说明(1):**
class PianoTeacher extends Human with TTeacher with PianoPlayer{...}的构造顺序为:**从左向右**。
即:先构造Human ,在构造TTeacher ,之后构造PianoPlayer。
说明(2):
在构造TTeacher的时候,发现它的父类Human已经被构造,就不会再重复构造(这是Scala特有的),
同理,构造TTeacher的时候,发现它的父类Human已经被构造,则不必重复构造。
实例二
object UseTrait {
def main(args:Array[String]): Unit ={
val t1=new PianoTeacher
t1.playPiano
t1.teach
val t2= new Human with TTeacher with PianoPlayer{
def teach={println("I'm teaching students.")}
}
t2.playPiano
t2.teach
}
}
![这里写图片描述](https://img-blog.csdn.net/20150721002828550)
AOP
package kmust.hjr.learningScala15
/**
* Created by Administrator on 2015/7/20.
*/
trait Action{
def doAction
}
trait TBeforeAfter extends Action{
abstract override def doAction: Unit ={
println("Initialization")
super.doAction
println("Destroyed")
}
}
class Work extends Action{
override def doAction=println("Working...")
}
object UseTrait {
def main(args:Array[String]): Unit ={
val work=new Work with TBeforeAfter
work.doAction
}
}
![这里写图片描述](https://img-blog.csdn.net/20150721003010147)
完整代码
package kmust.hjr.learningScala15
/**
* Created by Administrator on 2015/7/20.
*/
class Human{
println("Human")
}
trait TTeacher extends Human{
println("TTeacher")
def teach
}
trait PianoPlayer extends Human{
println("PianoPlayer")
def playPiano={println("I'm playing piano.")}
}
class PianoTeacher extends Human with TTeacher with PianoPlayer{
override def teach={println("I'm training students. ")}
}
trait Action{
def doAction
}
trait TBeforeAfter extends Action{
abstract override def doAction: Unit ={
println("Initialization")
super.doAction
println("Destroyed")
}
}
class Work extends Action{
override def doAction=println("Working...")
}
object UseTrait {
def main(args:Array[String]): Unit ={
val work=new Work with TBeforeAfter
work.doAction
}
}
附件 :
![这里写图片描述](https://img-blog.csdn.net/20150721232807068)