Scala Traits
2018-01-15 21:50 更新
Scala Traits
Traits就像Java中的接口,它也可以包含代码。
在Scala中,当一个类从trait继承时,它实现trait的接口,并继承trait中包含的所有代码。
在Scala中,traits可以继承类。
当一个类继承一个trait作为其父类时,也使用关键字extends。
即使当类使用with关键字在其他traits中混合时,也使用关键字extends。
此外,当一个trait是另一个trait或类的子对象时使用extends。
例子
trait flying { def fly() = println("flying") } trait gliding { def gliding() = println("gliding") } class Vehicle (speed : Int){ val mph :Int = speed def race() = println("Racing") } class Car (speed : Int) extends Vehicle(speed) { override val mph: Int= speed override def race() = println("Racing Car") } class Bike(speed : Int) extends Vehicle(speed) { override val mph: Int = speed override def race() = println("Racing Bike") } class AirCraft(speed : Int) extends Vehicle(speed) with flying with gliding{ override val mph: Int = speed override def race() = println("Racing") override def fly() = println("Flying") override def gliding() = println("Gliding") } object Main extends App { val vehicle1 = new Car(200) val vehicle2 = new Bike(100) val vehicle3 = new AirCraft(300) vehicle3.fly() val vehicleList = List(vehicle1, vehicle2, vehicle3) println(vehicleList); val fastestVehicle = vehicleList.maxBy(_.mph) println(fastestVehicle); }
以上内容是否对您有帮助:
← Scala 对象
更多建议: