一、Scala特质规则:
1、Scala特质是代码重用的基本单元,可以同时拥有抽象方法和具体方法;
2、Scala中一个类只能继承自一个超类,却可以混入多个特质(多继承);
3、特质像抽象类一样也可以包含非抽象程序员,但是不需要abstract关键字;
4、特质可以使用extents继承其他的特质,并且重载父特质的抽象方法,而且还可以继承类;
5、特质的定义体就相当于主构造器,与类不同的是,不能给特质的主构造器提供参数列表,而且也不能为特质定义辅助构造器;
6、如果特质继承自某个父类,则无法向该父类构造器传递参数,这就要求特质继承的父类必须有一个无参数的构造器;
7、特质定义好之后就可以使用extents或with关键字,把它混入到类中;
8、当把特质混入类中时,类必须实现特质中的抽象成员,除非该类为抽象类;
9、如果要混入多个特质,可以连续使用多个with;
二、实例:
trait T1 {def fly()
}trait T2 extends T1 {def move()def fly(): Unit = {println("I can fly")}
}
trait Flyable {var height:Int //抽象字段def fly() //抽象方法def breathe(): Unit ={println("I can breathe")}
}trait Color {val featherColor:Stringdef info(): Unit ={println("the Color of feather is:"+featherColor)}
}class Animal(name:String) {def animal_info(): Unit ={println("I am the animal of "+ name)}
}class Bird(b_height:Int)extends Animal("Bird")with Flyable with Color {var height:Int=b_height //var修饰的字段不叫重载,叫修改值。val featherColor: String = "red" //重载val修饰的字段def fly(): Unit = {println("I can fly this height of "+height+" m")}
}object Main extends App {val b = new Bird(30)b.animal_info()b.fly()b.info()
}
I am the animal of Bird
I can fly this height of 30 m
the Color of feather is:red
三、可以在类的定义中混入特质,还可以在实例某一类型时混入特质,这时只能用with关键字,而不能使用extents
trait Color {val featherColor:Stringdef info(): Unit ={println("the Color of feather is:"+featherColor)}
}class Animal(name:String) {def animal_info(): Unit ={println("I am the animal of "+ name)}
}object Main extends App {val d = new Animal("dog") with Color{val featherColor: String = "Yellow"}d.animal_info()d.info()
}
I am the animal of dog
the Color of feather is:Yellow
四、不能用new实例化特质,但可以使用多态特性
trait Flyable {var height:Int //抽象字段def fly() //抽象方法def breathe(): Unit ={println("I can breathe")}
}class Bird(b_height:Int) extends Flyable {var height:Int=b_height //var修饰的字段不叫重载,叫修改值。def fly(): Unit = {println("I can fly this height of "+height+" m")}}object Main extends App {val d:Flyable=new Bird(70)d.fly()d.breathe()
}
I can fly this height of 70 m
I can breathe
注意:
(1)此种情况,只适用继承单个特质;
(2)继承一个特质时只能使用extents,超出一个的使用with;