在scala中有的时候用extends有的时候用with,到底该用什么呢?
请看下面用例
trait Mytrait1{
def doSomething(str:String):Unit={
println(s"$str is doing")
}
}
trait Mytrait2{
def forfun():Unit
}
class Myclass1 extends Mytrait1{
}
class Myclass2{}
class Myclass3 extends Mytrait1 with Mytrait2{
override def forfun(): Unit = ???
}
val test = new Myclass2 with Mytrait2{
@Override
override def forfun(): Unit = {
println("666")
}
}
val test2 = new Myclass1
test forfun()
test2 doSomething("Test")
这里我们声明了特质Mytrait1,Mytrait2,和Myclass(1~3)这里Myclass继承了Mytrait1的特质,用了extends关键字,Myclass3继承了Mytrait1,和Mytrait2特质,第一个trait之前用了extends而第二个trait之前用了with,而实例化Myclass的时候在trait之前又用了with关键字。
这里特意声明一下: 如果是待声明的类没有扩展其他类只是或入了一些trait那么必须用extends关键字,并把它用在第一个trait之前而其它的trait之前用with关键字,就像Myclass3, 如果在实例化某一个类型的时候想要混入某一个特质,这个时候要用with关键字,如new Mycalss2这一个声明一样