1.定义
Scala中的特质 类似Java中的接口, 最主要不同点 Java接口中不能定义具体对象和方法 ,
而 Scala中的接口 可以定义抽象 和 具体的对象方法
2. 一个类只能继承一个超类,但是可以混入多个特质
使用extends 继承父类
使用with 混入特质,并且 可以混入多个特质
eg1:
//定义一个 特质Runable
trait Runable{
def category:String
def run(): Unit ={
printf("%s can run",category)
}
}
//定义一个特质Flyable
trait Flyable {
def category: String
def fly(): Unit = {
printf("%s can fly", category)
}
}
//定义一个 抽象类Animal
abstract class Animal(val theName:String){
def info()
}
//定义一个 具体类 Dog 继承父类 Animal,混入特质 Runable
case class Dog() extends Animal("Dog") with Runable{
override def category: String = "哺乳动物"
override def info(): Unit = {
printf("the category is %s, and the name is %s \n",category,theName)
}
}
//实例化一个Dog 类
val erHa = Dog()
erHa.info() //调用重写后的 info 方法
erHa.run() //调用特质 Runable 中的方法
输出:
eg2: