Scala吧~  - 讨论区

标题:Scala Tutorial 020:Traits的概念与使用方法

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哲思注册吗?现在 注册 !

    Zeuux © 2024

    京ICP备05028076号