Scala特质

Scala特质

特质的功能:

  • 定义抽象方法
  • 提供具体方法实现

特质是混入,可以重用特质当中的一些方法字段,间接实现多重继承。

trait Flyable {
  var maxFlyHeight: Int //抽象字段
  def fly() //抽象方法
  def breathe(): Unit = { //具体方法
    println("I can breathe")
  }
}
  • 特质中定义抽象成员时不需要加abstract。
  • 只要不给特质定义方法体、字段初值,它就是一个抽象的。
  • 特质下面还可以继承其它特质。

关键字

利用withextends两个关键字可以将特质混入(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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值