scala特质
1.scala中不支持多继承类,但是可以多继承特质
2.当做接口使用的特质
//特质可以同时拥有抽象方法和具体方法 trait Logger { def log(msg: String) //抽象方法 无需使用abstract关键字 } class ConsoleLogger extends Logger with Serializable with Cloneable { //多个特质使用with连接 override def log(msg: String): Unit = { println(msg) } }
3.带有具体实现的特质
trait ConsoleLogger { def log(msg: String) { println(msg) } } class Account extends ConsoleLogger { //ConsoleLogger的功能混入Account类中 }
4.带有特质的对象
trait ConsoleLogger { def log(msg: String) { println(msg) } } class Account { } object Test extends App { val account = new Account with ConsoleLogger account.log("....") }
5.叠加在一起的特质
trait Logged { def log(msg: String){println(msg)} } //给日志消息添加时间戳 trait TimestampLogger extends Logged { override def log(msg: String): Unit = super.log(new java.util.Date() + " " + msg) } //截断冗长的日志消息 trait ShortLogger extends Logged { val maxLength = 15 override def log(msg: String): Unit = { if (msg.length < maxLength) { super.log(msg) } else { super.log(msg.substring(0, msg.length - 3)) } } } class Account { } class SavingsAccount extends Account { } object Test extends App { val acct1 = new SavingsAccount with TimestampLogger with ShortLogger //从右向左执行 acct1.log("abcdefg") }
6.特质中重写抽象方法
trait Logged { def log(msg: String) //抽象方法 } trait TimestampLogger extends Logged { override def log(msg: String): Unit = super.log(new java.util.Date() + " " + msg) } class Account {} object Test extends App { val account = new Account with TimestampLogger account.log("a") Error:(7, 47) method log in trait Logged is accessed from super. It may not be abstract unless it is overridden by a member declared `abstract' and `override' override def log(msg: String): Unit = super.log(new java.util.Date() + " " + msg) }
trait Logged { def log(msg: String) //抽象方法 } trait TimestampLogger extends Logged { abstract override def log(msg: String): Unit = super.log(new java.util.Date() + " " + msg) } class Account {} object Test extends App { }
7.当做富接口使用的特质
trait Logged { def log(msg: String) def info(msg: String) { log("info: " + msg) } def warn(msg: String) { log("warn: " + msg) } def severs(msg: String) { log("severs: " + msg) } } class Account extends Logged { override def log(msg: String): Unit = { println(msg) } } object Test extends App { }
10.特质构造顺序
/* 特质构造顺序 1.超类构造器 2.特质构造器在超类构造器之后,类构造器之前 3.特质由左到右被构造 4.每个特质中父特质先被构造 5.多个特质公用一个父特质,父特质只会被构造一次 6.所有特质构造完成,子类被构造 */ trait Logger { } trait FileLogger extends Logger {} trait ShortLogger extends Logger {} class Account {} class SavingsAccount extends Account with FileLogger with ShortLogger {} /* 1.Account(超类) 2.Logger(第一个特质父特质) 3.FileLogger(第一个特质) 4.ShortLogger(第二个特质) 父特质已经被构造 5.SavingsAccount(类) */