Trait 特质
- Traits 封装了方法和变量,和 Interface 相比,它的方法可以有实现,这一点有点和抽象类定义类似;
- Scala 中类继承为单一继承,但是可以和多个 Trait 混合,这些 Trait 定义的成员变量和方法也就变成了该类的成员变量和方法;
- 创建类的时候可以使用 extends 或 with 来混合一个 trait;
- Traits 也算是继承制的父类,所以可以用 Traits 引用来接收子类对象(多态)
- Trait 不能有任何“类”参数
package test
object MyTest extends Super {
override def main(args: Array[String]): Unit = {
val t: Test = new MyTest()
t.hello()
}
}
trait Test {
def hello(): Unit = println("hello scala")
}
class MyTest extends AnyRef with Test {
}