1.trait的使用
(1)像java中定义接口一样进行使用,当实现trait的时候,如果实现类没有继承其他类,那么实现类,ConcreateLogger需要extends 一个trait(Logger),如果已经有一个trait或有extends那么就用with继承接口Cloneable,在with后面可以有多个接口,中间用逗号进行分割。
(2)混入
(2.1)对trait(Logger)中的方法进行实现在子类trait(TraitLogger)中
(2.2)实现类ConcreateLogger必须继承特质Logger
(2.3)ConcreateLogger中的方法调用log方法,实际调用的
TraitLogger中的log方法
2.实例
(1)像java中接口一样进行使用
package
com.jn.scala.oop
/**
* Created by JN on 2015/10/28.
*/
trait Logger{ // 指定关键子 trait
def log(msg : String ) //
}
class ConcreateLogger extends Logger with Cloneable{ // 第一次使用 trait, 左侧没有 trait 那就用 extends, 如果有就用 with
override def log(msg: String ) = println( "log:" + msg)
def concreateLog: Unit ={
log( "It's me" )
}
}
object UseTrait {
def main(args: Array[ String ]) {
val log = new ConcreateLogger
log.concreateLog
}
}
object
UseTrait {
def main(args: Array[ String ]) {
val log = new ConcreateLogger
log.concreateLog
}
def main(args: Array[ String ]) {
val log = new ConcreateLogger
log.concreateLog
}
}
运行结果
log:It's me
package
com.jn.scala
/**
* Created by jn on 2015/10/28.
*/
trait Logger{ //指定关键子trait
// def log(msg : String)//
def log(msg : String ){}
}
trait TraitLogger extends Logger{ //对象混入,类型要一致,进行覆盖
override def log(msg : String ): Unit ={
println( "TraitLogger log content is " + msg)
}
}
class ConcreateLogger extends Logger with Cloneable{ //第一次使用trait,左侧没有trait那就用extends,如果有就用with
override def log(msg: String ) = println( "log:" + msg)
def concreateLog: Unit ={
log( "It's me" )
}
}
object UseTrait {
def main(args: Array[ String ]) {
// val log = new ConcreateLogger
// log.concreateLog
val log = new ConcreateLogger with TraitLogger //将log实现进行混入
log.concreateLog
}
/**
* Created by jn on 2015/10/28.
*/
trait Logger{ //指定关键子trait
// def log(msg : String)//
def log(msg : String ){}
}
trait TraitLogger extends Logger{ //对象混入,类型要一致,进行覆盖
override def log(msg : String ): Unit ={
println( "TraitLogger log content is " + msg)
}
}
class ConcreateLogger extends Logger with Cloneable{ //第一次使用trait,左侧没有trait那就用extends,如果有就用with
override def log(msg: String ) = println( "log:" + msg)
def concreateLog: Unit ={
log( "It's me" )
}
}
object UseTrait {
def main(args: Array[ String ]) {
// val log = new ConcreateLogger
// log.concreateLog
val log = new ConcreateLogger with TraitLogger //将log实现进行混入
log.concreateLog
}
}
//运行结果
TraitLogger log content is It's me
TraitLogger log content is It's me