标签:blog ar java sp div log ef bs new
// 类接口,但是可以实现方法 // 作用 多重继承 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 ") } } // class abstract 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类的子类, 给程序提供了相对多的灵活性
标签:blog ar java sp div log ef bs new
原文地址:http://www.cnblogs.com/chengxin1982/p/4035717.html