2014年03月12日 星期三 10:07
在Scala中,Traits相当于其他高级语言中的interface的概念。
Similar to interfaces in Java, traits are used to define object types by specifying the signature of the supported methods. Unlike Java, Scala allows traits to be partially implemented; i.e. it is possible to define default implementations for some methods. In contrast to classes, traits may not have constructor parameters.
示例代码如下:
trait Speaker { def sayHello(name : String) } class AutoSpeaker extends Speaker { private var gstr="Hello, "; def this(greeting : String){ this() gstr=greeting } def sayHello(name : String){ println(gstr + name + ".") } } object SimpleTrait { def main(args: Array[String]): Unit = { var sp=new AutoSpeaker() sp.sayHello("mengguang") sp=new AutoSpeaker("Good afternoot, ") sp.sayHello("mengkang") } }
参考资料:
http://www.scala-lang.org/old/node/126
http://en.wikipedia.org/wiki/Trait_%28computer_programming%29
Zeuux © 2024
京ICP备05028076号