我正在阅读此链接中的示例http://www.tutorialspoint.com/scala/scala_classes_objects.htm 示例:
class Point(val xc: Int, val yc: Int) {
var x: Int = xc
var y: Int = yc
def move(dx: Int, dy: Int) {
x = x + dx
y = y + dy
println ("Point x location : " + x);
println ("Point y location : " + y);
}
}
class Location(override val xc: Int, override val yc: Int,
val zc :Int) extends Point(xc, yc){
var z: Int = zc
def move(dx: Int, dy: Int, dz: Int) {
x = x + dx
y = y + dy
z = z + dz
println ("Point x location : " + x);
println ("Point y location : " + y);
println ("Point z location : " + z);
}
}
object Test {
def main(args: Array[String]) {
val loc = new Location(10, 20, 15);
// Move to a new location
loc.move(10, 10, 5);
}
}
我在类位置构造函数中不理解override关键字的效用! 为什么会提到它,因为我们有延伸? 谢谢!
答案 0 :(得分:4)
鉴于
scala> class A(val a: Int)
defined class A
如果您尝试像这样定义B
:
scala> class B(val a: Int) extends A(a)
<console>:11: error: overriding value a in class A of type Int;
value a needs `override' modifier
class B(val a: Int) extends A(a)
编译器抱怨,因为看起来您正试图在类a
中定义成员B
,并且它已经通过继承(来自A
)存在。在这种情况下,您需要添加override
以明确您的意图:
scala> class B(override val a: Int) extends A(a)
defined class B
更具体地说,如果您要覆盖抽象成员,则不必提供override
:
scala> trait A { def a: Int }
defined trait A
scala> class B(override val a: Int) extends A
defined class B
scala> class B(val a: Int) extends A
defined class B
但是,为了避免在混合特征时出现意外覆盖,Scala会通过要求明确override
来保护您。
考虑这个例子:
这里没问题:
scala> trait A { def a: Int = 1 }
defined trait A
scala> class B
defined class B
scala> new B with A
res0: B with A = $anon$1@3e29739a
你从歧义中得救了:
scala> trait A { def a: Int = 1 }
defined trait A
scala> class B { def a: Int = 2 }
defined class B
scala> new B with A
<console>:13: error: <$anon: B with A> inherits conflicting members:
method a in class B of type => Int and
method a in trait A of type => Int
(Note: this can be resolved by declaring an override in <$anon: B with A>.)
new B with A
^
手动解决冲突:
scala> trait A { def a: Int = 1 }
defined trait A
scala> class B { def a: Int = 2 }
defined class B
scala> new B with A { override val a = super[B].a }
res6: B with A{val a: Int} = $anon$1@76f6896b