class Human {
println("Human")
}
/*
* 和java不同,trait可以继承普通的类
* trait不能实例化
*/
trait TTeacher extends Human {
println("TTeacher")
def teach
}
trait PianoPlayer extends Human {
println("PianoPlayer")
def playPiano = {
println("I am playing piano")
}
}
/*
* 多重继承
* 构造顺序从左往右
* scala规则:不会重复构造,如下面的程序TTeacher、PianoPlayer不会重复构造Human
*/
class PianoTeacher extends Human with TTeacher with PianoPlayer {
override def teach = {
println("I am training students")
}
}
object Test {
def main(args: Array[String]) {
// def t1 = new PianoTeacher
// t1.playPiano
// t1.teach
//创建对象时混入特质,要重写trait中的抽象方法
def t2 = new Human with TTeacher with PianoPlayer {
override def teach = {
println("t2: I am training studend")
}
}
t2.playPiano
t2.teach
}
}
scala基础17-多重继承/混入特质需重写抽象方法
最新推荐文章于 2022-07-12 14:47:40 发布