(一)trait定义和作用
Scala没有Java中接口的概念,所以Scala的trait就类比Java中的接口。
Scala的特质定义如下:
trait identified {
属性; 方法
}
trait是关键字,identified 表示一个合法的标记。
作用:封装成员和方法,供其他类来实现。它可以实现多继承!
(二)实现单个特质
用一个类去实现单个特质。
(三)实现多个特质
格式:类名 extends 特质1 with 特质2 with 特质3 其中多个特质的顺序可以交换。
/*特质
trait:实现多继承
*/
object f1117 {
trait BeautifulEye {
val eye:String = "眼睛漂亮"
}
trait Tall {
val height:String = "大高个"
}
//继承 with
class Child extends BeautifulEye with Tall{
}
def main(args: Array[String]): Unit = {
val child = new Child()
println(child.eye)
println(child.height)
}
//运行结果:
眼睛漂亮
大高个
(四)特质成员的处理方式
1.特质中的抽象属性:可以通过val或var修饰来重写
2.特质中的抽象方法:一定要实现方法体。
3.特质中的具体属性:重写var不需override和var,只需要属性名即可;重写val需要加上override关键字。
4.特质中的具体方法:使用override重写,且保持名称,参数,返回值一致。
总结:
- trait中可有抽象 也可有具体。
- 它的子类必须实现抽象的(属性,方法)。
/*特质
trait:实现多继承
1.具体属性 抽象属性
2.具体方法 抽象方法
总结:trait中可有抽象 也可有具体
它的子类必须实现抽象的(属性,方法)
*/
object f1117 {
trait BeautifulEye {
val eye:String = "眼睛漂亮" //具体属性
}
trait Tall {
val height:String = "大高个"
def run():Unit = {
println("run...")
}
def jump():Unit
}
//继承 with
class Child extends BeautifulEye with Tall{
val name:String = "小花" //实现抽象属性
def jump():Unit = { //实现抽象方法
println(s"${name},jump...")
}
}
def main(args: Array[String]): Unit = {
val child = new Child()
println(child.eye)
println(child.height)
child.run()
child.jump()
}
//运行结果:
眼睛漂亮
大高个
run...
小花,jump...