标签:
package examples //特质的基本使用 trait Logger { def log(msg:String) //不定义,抽象方法 } class ConsoleLogger extends Logger { def log(msg:String){println(msg)} //重写抽象方法不需要override } class Animal {} import scala.util.logging.Logged class Cat extends Animal with Logged { def sayHello= { log("Fuck!") } } trait ConsoleLogged extends Logged { override def log(msg:String){println(msg)} //因为Logged中log不是抽象方法,所以需要override } //Ordered接口的使用 class Rational(n:Int,d:Int) extends Ordered[Rational] { def numer =n def demon = d def compare(that:Rational)= { this.numer*that.demon - that.numer*this.demon } } //特质作堆叠 abstract class IntQueue { def get():Int def put(x:Int) } import scala.collection.mutable.ArrayBuffer class BasicIntQueue extends IntQueue { private val buffer = new ArrayBuffer[Int] def get=buffer.remove(0) def put(x:Int)={buffer+=x} } trait Incrementing extends IntQueue { abstract override def put(x:Int) {super.put(x+1)} } trait Filtering extends IntQueue { abstract override def put(x:Int) { if(x>=0) super.put(x) } } object Example10 extends App{ var cat = new Cat cat.sayHello //没输出,因为Logged里面的log没有输出 println("------------------------") cat = new Cat with ConsoleLogged cat.sayHello //有输出,因为ConsoleLogged里面的重写了log,覆盖了原Logged println("------------------------") val half = new Rational(1,2) val third = new Rational(1,3) println(half>third) println("------------------------") var queue = new BasicIntQueue with Incrementing with Filtering //先过滤再递增再进队列 queue.put(-1) queue.put(0) queue.put(1) println(queue.get) println(queue.get) println("------------------------") queue = new BasicIntQueue with Filtering with Incrementing //先递增再过滤再进队列 queue.put(-1) queue.put(0) queue.put(1) println(queue.get) println(queue.get) //从上面可以看出来,越在后面的特质越先起作用 //如果她调用了super,然你就会接着调用她左边的特质的对应方法 }
------------------------ Fuck! ------------------------ true ------------------------ 1 2 ------------------------ 0 1
标签:
原文地址:http://blog.csdn.net/lingerlanlan/article/details/44158021