标签:
1 package com.swust.example 2 3 object TraitDemo2 extends App{ 4 5 //抽象类 6 abstract class Writer { 7 def writeMessage(message: String) 8 } 9 /** 10 * 继承这个抽象类,并且用super调用了这个抽象方法 11 * scala要求将方法声明为abstract override 12 * override告诉scala要为基类的一个已知方法提供一个实现 13 * abstract表示这个方法实际最后的终极实现要由混入这个trait的类提供 14 */ 15 trait UpperCaseWriter extends Writer{ 16 abstract override def writeMessage(message: String)={ 17 super.writeMessage(message.toUpperCase) 18 } 19 } 20 /** 21 * 为了调用super.writeMessage,scala做了两件事情 22 * 1、对这个调用进行了延迟绑定 23 * 2、要求混入这些trait的类提供该方法的实现 24 */ 25 trait WordFilterWriter extends Writer{ 26 abstract override def writeMessage(message: String)={ 27 super.writeMessage(message.replace("stupid","s-----")) 28 } 29 } 30 class StringWriterDelegate extends Writer{ 31 val writer = new java.io.StringWriter 32 //实现抽象类的方法,不用override 33 def writeMessage(message: String) = writer.write(message) 34 override def toString(): String = writer.toString 35 } 36 //创建实例时混入trait 37 val first = new StringWriterDelegate with UpperCaseWriter with WordFilterWriter 38 val last = new StringWriterDelegate with WordFilterWriter with UpperCaseWriter 39 first.writeMessage("there is no sin except stupidity") 40 last.writeMessage("there is no sin except stupidity") 41 println(first) 42 println(last) 43 44 }
标签:
原文地址:http://www.cnblogs.com/sunfie/p/5077262.html