在scala中,trait相当于java中的interface关键字,可以用来定义接口,但是trait除了定义接口,还有许多强大功能
trait Logger{
// def log (msg : String)
def log (msg : String){} //与java不同的是,trait允许方法有实现
}
class ConcreteLogger extends Logger with Cloneable{ //with关键字可以用来使用其它trait
override def log(msg : String) = println("Log: " + msg) //子类覆盖trait方法
def concreteLog{
log("It's me !!!")
}
}
object UseTrait extends App{
val logger = new ConcreteLogger
logger.concreteLog
}
结果:Log: It's me !!!
trait Logger{
def log (msg : String){}
}
class ConcreteLogger extends Logger with Cloneable{ //with关键字可以用来使用其它trait
//这里没有覆盖trait的log方法
def concreteLog{
log("It's me !!!")
}
}
trait TraitLogger extends Logger{ //定义另一个子trait,覆盖父trait的方法
override def log (msg : String){
println(" TraitLogger Log content is : " + msg)
}
}
object UseTrait extends App{
val logger = new ConcreteLogger whit TraitLogger //将具体实现的trait动态混入到对象中
logger.concreteLog
}
结果: TraitLogger Log content is : It's me !!!
所以,一般在trait中做很多不同的工具方法,然后根据运行情况混入不同的trait到对象中。
网友评论