Scala特质
特质的功能:
- 定义抽象方法
- 提供具体方法实现
特质是混入,可以重用特质当中的一些方法字段,间接实现多重继承。
trait Flyable {
var maxFlyHeight: Int //抽象字段
def fly() //抽象方法
def breathe(): Unit = { //具体方法
println("I can breathe")
}
}
- 特质中定义抽象成员时不需要加abstract。
- 只要不给特质定义方法体、字段初值,它就是一个抽象的。
- 特质下面还可以继承其它特质。
关键字
利用with
和extends
两个关键字可以将特质混入(mixin)到类中,相当于去继承了。
trait Flyable {
var maxFlyHeight: Int //抽象字段
def fly() //抽象方法
def breathe(): Unit = { //具体方法
println("I can breathe")
}
}
class Bird(flyHeight: Int) extends Flyable {
var maxFlyHeight: Int = flyHeight //重载特质的抽象字段
def fly(): Unit = {
printf("I can fly height of %d.\n", maxFlyHeight)
} //重载特质的抽象方法
}
object test_fly{
def main(args: Array[String]): Unit = {
val b=new Bird(100)
b.fly()
b.breathe()
}
}
out:
I can fly height of 100.
I can breathe
一个类去继承一个父类同时混入多个特质案例:
trait Flyable2 {
var maxFlyHeight: Int //抽象字段
def fly() //抽象方法
def breathe(): Unit = { //具体方法
println("I can breathe")
}
}
trait HasLegs{
val legs:Int //抽象字段
def move(){printf("I can walk with %d legs.\n",legs)}
}
class Animal(val category: String) {
def info() {println("This is a " + category)}
}
class Bird2(flyHeight: Int) extends Animal("Bird") with Flyable2 with HasLegs {
var maxFlyHeight: Int = flyHeight //重载特质的抽象字段
val legs = 2 //重载特质的抽象字段
def fly() {
printf("I can fly at the height of %d.\n", maxFlyHeight)
} //重载特质的抽象方法
}
object test_fly2{
def main(args: Array[String]): Unit = {
val b=new Bird2(108)
b.info
b.fly
b.move
}
}
out:
This is a Bird
I can fly at the height of 108.
I can walk with 2 legs.