scala学习-trait学习
来源:互联网 发布:淘宝a0图纸扫描仪 编辑:程序博客网 时间:2024/05/21 17:57
trait是scala中代码复用的基础单元。特质中封装了一些方法和字段,可以通过混入到类中来重用他们。定义trait的方法:
trait ConsoleLogger{
def logger(msg: String) = {println(msg)}
}
与类的继承不同,一个子类只能继承自唯一的超类,而一个类中可以混入多个特质。特质的定义与类定义除关键字不同以外,基本无大的差异。
特质同样也是类型,但是特质与类又有区别:
1.不可以带有任何“类”参数,即传递给类的主构造器任何参数。
2.在类中,super的调用是静态绑定的,而trait中调用super是动态绑定的。
比如说,先定义一个抽象类:
abstract class IntQueue { def get(): Int def put(x: Int)}
再定义一个类继承自IntQueue类,实现了该抽象类中的抽象方法get和put,且创建了一个私有字段buf。
class BasicIntQueue extends IntQueue{ private val buf = new ArrayBuffer[Int] def get() = buf.remove(0) def put(x: Int) { buf += x}}
定义一个trait,继承自IntQueue,并复写了超类中的put方法
trait Doubling extends IntQueue { abstract override def put(x: Int) { super.put(x * 2)}}
在上述的trait中调用的super是动态绑定的。当你定义下面类时
class MyQueue extends BasicIntQueue with Doubling
此时混入Doubling这个特质后,此时的super绑定的BasicIntQueue的put方法。
0 0
- scala学习-trait学习
- scala学习trait
- Scala学习--Trait
- Scala学习笔记5--Trait
- scala学习记录之trait
- scala学习之特质(trait)
- scala学习笔记3(trait)
- Scala 学习之 Class,Object, Trait
- scala学习之:trait的理解
- scala学习(十五)——trait
- sealed trait Scala学习笔记-面向对象篇
- Scala学习笔记12【继承、抽象类、trait实战】
- Scala学习笔记13【trait之多重继承、AOP实战】
- scala学习13之与trait同名的object对象
- scala学习(十五)——trait运行时装配
- Scala学习—面向对象编程之Trait
- Scala学习第十四天 Scala中作为接口的trait、在对象中混入trait代码实战
- 龟云狄眦-Scala学习札记【一】Scala中class、object、trait初识
- [交易策略]周线四进两出策略回测
- 最大网络流(Ford-Fulkerson算法)(hihicoder)
- session跨域共享
- _fastmath HAVE_DECL error
- 共享进程id,sharedpreferences 共享资源
- scala学习-trait学习
- BAPC2010-I Keylogger
- activemq - 集群 - 基于zookeeper的levelDB集群方式
- CodeForces 612D - The Union of k-Segments(模拟)
- A*寻路算法
- 前端开发不得不知道的十大ES6新特性
- java环境变量配置
- vim脚本调试
- C语言中extern的用法