(一) trait定义和作用
Scala没有Java中接口的概念,所以Scala的trait就类比Java中的接口。Scala的特质定义如下:
trait是关键字,identified 表示一个合法的标记。
作用:封装成员和方法,供其他类来实现。它可以实现多继承!
(二) 实现单个特质
trait BaseSoundPlayer {
def play(): Unit
def close
def see(): Unit = {
println("basesoundplayer see")
}
}
class MP3 extends BaseSoundPlayer{
def play(): Unit = {
println("mp3 play")
}
override def see():Unit = {
println("mp3 see....")
}
def close:Unit = {
println("close")
}
}
object TestTrait {
def main(args: Array[String]): Unit = {
val mp3 = new MP3()
mp3.see()
mp3.play()
}
}
(三) 实现多个特质
格式:类名 extends 特质1 with 特质2 with 特质3 其中多个特质的顺序可以交换。
object practice49 {
trait BeautifulEye {
val eye: String = "眼睛漂亮"
}
trait Tall {
val height:String = "大高个"
}
class Child extends BeautifulEye with Tall{
}
def main(args: Array[String]): Unit = {
val child = new Child()
println(child.eye)
println(child.height)
}
}