Scala的trait的运用和实例操作

//trait:特质(美丽,智慧,耐心)
//作用:(1) 当做接口来使用,实现多继承;(2) 当做抽象类,定义类的标准

//格式:trait 名字{属性 ,方法}
trait BackgroundPlayer {
  //  abstract class BackgroundPlayer(){} 这个括号里面可以传入参数,trait应用不可以
  //抽象属性
  val cd: String

  //抽象方法
  def play

  val color = "red" //具体属性

  def pause(): Unit = { //具体方法

  }
}

trait VideoPlayer{
  def playVideo
}

//子类继承特质,必须要实现所有的抽象的成员
class Mp3 extends BackgroundPlayer {
  val cd = "周杰伦"

  def play(): Unit = {
    println(s"Mp3 播放 ${cd}")
  }
}
//一个子类有多个父类 — 多继承
class Mp4 extends BackgroundPlayer with VideoPlayer{
  val cd="王杰"
  def play(): Unit ={
    println("mp3 播放器")
  }
   //播放视频
  def playVideo(): Unit ={
    println("Mp4 播放器 — 视频")
  }
}
object dgha {
  def main(args: Array[String]): Unit = {
    //trait 不能直接new
    //    new BackgroundPlayer()
//    val m1 = new Mp3()
//    m1.play()
    val m2=new Mp4()
    m2.play()
    m2.playVideo()
    
  }

package Scala3
//trait的加载顺序
//1.先执行父构造器,再执行子构造器
trait A051{
  println("A051")
}

trait AA051 extends A051{
  println("AA051")//1
}
trait AB051 extends A051{
  println("AB051")//2
}
trait B051{
  println("B051")
}
trait BA051 extends B051{
  println("BA051")
}
trait BB051 extends B051{
  println("BB051")
}
//2.有多个父构造器,按照从左到右的顺序,先执行左边的父构造器,再执行右边的父构造器
class AB extends AA051 with  BA051 with AB051 with BB051 {
  println("AB")//
}
object fh {
  def main(args: Array[String]): Unit = {
    new AB()
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值