Scala学习笔记05--特质
2015-03-27 17:01
302 查看
在 Java 或者 Scala 的类中,super.method() 这样的方法调用是静态绑定的,也就是说当你在代码中写下 super.method() 的时候就能明确是调用它的父类的 method() 方法。
然而,如果是在特质中写下了 super.method() 时,它的调用是动态绑定的。调用的实现奖在每一次特质被混入到具体类的时候才被决定。
直截的讲就是超靠近后面的特质越优先起作用。当你调用带混入的类的方法是,最右侧特质的方法首先被调用。如果那个方法调用了 super,它调用其左侧特质的方法。
object TraitTest {
def main(args: Array[String]): Unit = {
val person = new person with sayWorld with sayHello
person.say("hey: ")
}
abstract class animal() {
def say(something: String)
}
class person extends animal {
var word = "I am person! "
def say(something: String) {
word = word + something
print(word)
}
}
trait sayWorld extends animal {
abstract override def say(something: String) {
super.say(something + "world. ")
}
}
trait sayHello extends animal {
abstract override def say(something: String) {
super.say(something + "hello. ")
}
}
}
输出结果:I am person! hey: hello. world.
tips:1.trait里super是动态绑定的。
2.在这种方法上,打上abstract override标志。
然而,如果是在特质中写下了 super.method() 时,它的调用是动态绑定的。调用的实现奖在每一次特质被混入到具体类的时候才被决定。
直截的讲就是超靠近后面的特质越优先起作用。当你调用带混入的类的方法是,最右侧特质的方法首先被调用。如果那个方法调用了 super,它调用其左侧特质的方法。
object TraitTest {
def main(args: Array[String]): Unit = {
val person = new person with sayWorld with sayHello
person.say("hey: ")
}
abstract class animal() {
def say(something: String)
}
class person extends animal {
var word = "I am person! "
def say(something: String) {
word = word + something
print(word)
}
}
trait sayWorld extends animal {
abstract override def say(something: String) {
super.say(something + "world. ")
}
}
trait sayHello extends animal {
abstract override def say(something: String) {
super.say(something + "hello. ")
}
}
}
输出结果:I am person! hey: hello. world.
tips:1.trait里super是动态绑定的。
2.在这种方法上,打上abstract override标志。
相关文章推荐
- Scala学习笔记05--特质
- scala学习笔记——特质
- Scala学习笔记(3)-Scala特质
- 快学Scala学习笔记及习题解答(10-11特质与操作符)
- Scala学习笔记05--控制抽象
- Scala学习笔记——简化代码、柯里化、继承、特质
- scala 学习笔记(05) OOP(中)灵活的trait
- scala学习笔记11 特质
- Scala学习笔记05【Scala函数定义、流程控制、异常入门】
- Scala2.11.7学习笔记(六)Scala特质介绍
- Scala学习笔记05--控制抽象
- Scala学习笔记5 - 特质
- Scala学习笔记(三)类层级和特质
- scala学习笔记-特质
- Scala学习笔记--特质trait
- Scala学习笔记(七):Application特质
- Scala学习笔记--特质
- Scala学习笔记(八) - 特质
- Scala学习笔记(三)类层级和特质
- Scala 学习笔记(〇)