Scala中trait基本使用

35 阅读1分钟

trait定义

Scala的trait就类比Java中的接口。Scala的特质定义如下:

trait identified {  
    属性; 方法
}

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  其中多个特质的顺序可以交换

/*
 特质
 trait:实现多继承
 具体属性,抽象属性
 具体方法,抽象方法
 1.trait中可有抽象,也可有具体
 2.它的子类必须实现抽象的(属性,方法)

 */
object day31 {
  trait BeautifulEye {
     val eye:String="眼睛美丽"//具体属性
     val name: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()
  }

}