特质中可以定义具体字段,如果初始化了就是具体字段,如果不初始化就是抽象字段。
混入该特质的类就具有了该字段,字段不是继承,而是简单的加入类,是自己的字段,就好像copy了一下
trait Logger7 {
def log(msg: String)
//抽象字段
val x:Int
//非抽象字段
val y:Int = 10
}
trait ConsoleLogger7 extends Logger7 {
def log(msg: String) {
println(msg)
}
}
trait ShortLogger7 extends Logger7 {
val maxLength = 15
abstract override def log(msg: String) {
super.log(if (msg.length <= maxLength) msg else s"${msg.substring(0, maxLength - 3)}...")
}
}
class Account7 {
protected var balance = 0.0
}
class SavingsAccount7 extends Account7 with ConsoleLogger7 with ShortLogger7 {
var interest = 0.0
def withdraw(amount: Double) {
if (amount > balance) log("余额不足")
else balance -= amount
}
}
object Main7 extends App {
val acct = new SavingsAccount7
acct.withdraw(100)
println(acct.maxLength)
}