在Scala中,可以使用类或抽象类来扩展特征的数量。这被称为特质混合。对于扩展,只有特征,特征,类或抽象类的混合才有效。
如果未保留“特性混合”的顺序,则编译器将引发错误。它用于组成一个类。由于可以继承多个特征。
让我们看一些例子,以更好地理解该主题,
示例1:使用特征扩展抽象类
trait Bike {
def Bike() ;
}
abstract class Speed {
def Speed() ;
}
class myBike extends Speed with Bike {
def Bike() {
println("Harley Davidson Iron 883") ;
}
def Speed() {
println("Max Speed : 170 KmpH") ;
}
}
object myObject {
def main(args:Array[String]) {
val newbike = new myBike() ;
newbike.Bike() ;
newbike.Speed() ;
}
}输出结果
Harley Davidson Iron 883 Max Speed : 170 KmpH
示例2:扩展不带特征的抽象类
trait Bike {
def Bike() ;
}
abstract class Speed{
def Speed() ;
}
class myBike extends Speed {
def Bike() {
println("Harley Davidson Iron 883") ;
}
def Speed() {
println("Max Speed : 170 KmpH") ;
}
}
object myObject {
def main(args:Array[String]) {
val newbike = new myBike() with Bike;
newbike.Bike() ;
newbike.Speed() ;
}
}输出结果
Harley Davidson Iron 883 Max Speed : 170 KmpH