trait的基本使用

34 阅读1分钟

trait: 实现多继承

在前面的课程中,我们已经学习了很多类的相关知识了,在java中有接口这个概念,但是在scala没有接口,可它提供了trait(特质)来实现。

类名 extends 特质1 with 特质2 with 特质3其中多个特质的顺序可以交换。

/**
 * 特质
 * trait: 实现多继承
 */
  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)
  }
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...")
  }
}

// 注意:Scala入口方法需放在单例对象内
object TraitDemo {
  def main(args: Array[String]): Unit = {
    val child = new Child()
    println(child.eye)
    println(child.height)
    child.run()
    child.jump()
  }
}