scala> abstract class A
defined class A
scala> abstract class B
defined class B
scala> class C extends A
defined class C
scala> trait A
defined trait A
scala> trait B
defined trait B
scala> class C extends A with B
defined class C
scala> class C with A with B
<console>:1: error: ';' expected but 'with' found.
class C with A with B
^
cala> abstract class Employee(id:String,name:String)
defined class Employee
scala> trait Employee(id:String,name:String)
<console>:1: error: traits or objects may not have parameters
trait Employee(id:String,name:String)
^
抽象類別的 super :
scala> abstract class Counter {
| def count(num1: Int , num2: Int) : Unit
| }
defined class Counter
scala> class MyCounter extends Counter {
| var sum = 0
| def count(num1: Int , num2: Int): Unit = sum = num1 + num2
| def getSum = sum
| }
defined class MyCounter
trait 的 super 由於是動態的所以 with 的順序不同會影響 super 最後的結果,所以又稱 stackable modifications (堆疊修飾) :
scala> abstract class Counter {
| def count(num1: Int , num2: Int) : Unit
| }
defined class Counter
scala> class MyCounter extends Counter {
| var sum = 0
| def count(num1: Int , num2: Int): Unit = sum = num1 * num2
| def getSum = sum
| }
defined class MyCounter
scala> trait Counter1 extends MyCounter {
| abstract override def count(num1:Int , num2:Int) = {
| if(num1 < 0 || num2 < 0) {
| super.count(num1,num2)
| } else {
| sum = num1 + num2
| }
| }
| }
defined trait Counter1
scala> trait Filter1 extends MyCounter {
| abstract override def count(num1:Int , num2:Int) = {
| if(num1 < 0 || num2 < 0) {
| super.count(num1,num2)
| } else {
| sum = num1 + num2 * 2
| }
| }
| }
defined trait Filter1
stackable modifications 會從最右邊開始,例如下面 coutner1 這個物件,
Filter1 的 super 會呼叫 Counter1 的 method ,Counter1 的 super 會呼叫 MyCounter 的 method :
scala> val counter1 = (new MyCounter with Counter1 with Filter1)
counter1: MyCounter with Counter1 with Filter1 = $anon$1@a5e8260
scala> counter1.count(1,2)
scala> counter1.sum
res1: Int = 5
scala> counter1.count(-2,5)
scala> counter1.sum
res3: Int = -10
counter2 這個物件,Counter1 的 super 會呼叫 Filter1 的 method ,Filter1 的 super 會呼叫 MyCounter 的 method :
scala> val counter2 = (new MyCounter with Filter1 with Counter1)
counter2: MyCounter with Filter1 with Counter1 = $anon$1@167bb934
scala> counter2.count(1,2)
scala> counter2.sum
res7: Int = 3
scala> counter2.count(-1,2)
scala> counter2.sum
res9: Int = -2