Scala中的Trait方法

版权声明:未经允许,随意转载,请附上本文链接谢谢(づ ̄3 ̄)づ╭❤~
https://blog.csdn.net/xiaoduan_/article/details/80983658

Scala中的Trait方法

Scala Trait(特征) 相当于 Java 的接口,实际上它比接口还功能强大。

与接口不同的是,它还可以定义属性和方法的实现。

一般情况下Scala的类只能够继承单一父类,但是如果是 Trait(特征) 的话就可以继承多个,从结果来看就是实现了多重继承。

Trait(特征) 定义的方式与类类似,但它使用的关键字是 trait,如下所示:

package com.anthony

/**
  * @ Description:
  * @ Date: Created in 10:41 10/07/2018
  * @ Author: Anthony_Duan
  */
object trait_test {
  def main(args: Array[String]): Unit = {
    val flyFish = new FlyFish
    flyFish.eat
    flyFish.fly
    flyFish.swim
  }

}

trait Flyable{
  def fly
  def eat = println(" i can eat")
}

trait swimable{
  def swim
}

class FlyFish extends Flyable with swimable {
  override def fly: Unit = {
    println("i can fly")
  }

  override def swim: Unit = {
    println(" i can swim")
  }
}

猜你喜欢

转载自blog.csdn.net/xiaoduan_/article/details/80983658