让我解释一下我在scala中对多重继承的观察:
在类的scala中,多重继承是不可能的。我可以理解这是由于“钻石问题”的http://stackoverflow.com/questions/2064880/diamond-problem,所以下面的代码不能编译
class High {
def confuse(){
println("High::I will confuse you later")
}
}
class MiddleLeft extends High {
override def confuse(){
println("MiddleLeft::I will confuse you later")
}
}
class MiddleRight extends High{
override def confuse(){
println("MiddleRight::I will confuse you later")
}
}
// Below code does not compile
class LowLeft extends MiddleRight with MiddleLeft{
def calConfuse(){
confuse()
}
}现在,特征可能有了具体的类。但它支持多重继承,因为特征如何扩展的顺序关系到解决菱形问题的顺序,因此下面的代码可以正常工作
trait High {
def confuse(){
println("High::I will confuse you later")
}
}
trait MiddleLeft extends High {
override def confuse(){
println("MiddleLeft::I will confuse you later")
}
}
trait MiddleRight extends High{
override def confuse(){
println("MiddleRight::I will confuse you later")
}
}
class LowLeft extends MiddleRight with MiddleLeft{
def calConfuse(){
confuse()
}
}
class LowRight extends MiddleLeft with MiddleRight{
def calConfuse(){
confuse()
}
}
object ConfuseTester extends App{
val lowLeft:LowLeft=new LowLeft()
lowLeft.confuse() //prints>>>MiddleLeft::I will confuse you later
val lowRight:LowRight=new LowRight()
lowRight.confuse()//prints>>>MiddleRight::I will confuse you later
}我的问题是,为什么类的多重继承不像特征那样遵循相同的策略(如何扩展的顺序)
发布于 2016-12-10 13:18:54
每个Scala类都被编译成一个JVM类,并且JVM不支持类的多重继承。
https://stackoverflow.com/questions/41070383
复制相似问题