首页 > 代码库 > 学习scala trait

学习scala trait

 
// 类接口,但是可以实现方法// 作用 多重继承trait traitA{  val tnum: Int  def log(msg: String): Unit ={    println("log : " + msg)  }}trait traitB extends traitA{  def test: Unit ={    log("trait tb call ")  }}trait traitC extends traitB{  override def test: Unit ={    log("trait tc call ")  }}// classabstract  class ClassA {  def abstractMethod}class classB extends ClassA{   def abstractMethod: Unit ={    println("ClassB is call")  }}// 测试多重继承class classC extends classB with traitB{  val tnum:Int = 3  def calltrait(): Unit ={    test  }  def callabstract(): Unit ={    abstractMethod  }}object Testtrait extends  App{  var c1 = new classC  c1.calltrait()  c1.callabstract()  var c = new classC with traitC  c.calltrait()  c.callabstract()  println(c.tnum)}

  

运行结果:

log : trait tb call
ClassB is call
log : trait tc call
ClassB is call
3

由此可以看出在scala中,创建trait派生类对象,是可以再次指定继承的trait类的子类,  给程序提供了相对多的灵活性

学习scala trait