scala - 继承 : override in class constructor

标签 scala inheritance overriding

我正在阅读此链接中的示例 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 关键字的用途! 为什么要提到它,因为我们在这里有一个扩展? 谢谢!

最佳答案

给定

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)

编译器提示,因为它看起来像你试图在类 B 中定义一个成员 a 并且它已经通过继承存在(来自 A).在这种情况下,您需要添加 override 以明确说明您的意图:

scala> class B(override val a: Int) extends A(a)
defined class B

更具体地说,如果您要覆盖抽象成员,则不必提供覆盖:

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

但是,为了避免在混入 trait 时发生意外覆盖,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

关于scala - 继承 : override in class constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35148457/

相关文章:

scala - 为什么方法需要 'abstract override' 修饰符

java - 使用父类(super class) "protected final"方法为子类保留公共(public)代码

java - 从对象类型的角度来看,子类是否等同于它们的 racine 类?

Hibernate Single_Table 持久化 实体没有在子类上定义主键属性

java - @override 在 android 中使用 onDraw 导致错误

scala - Scala 中多个参数列表和每个列表多个参数有什么区别?

scala - Playframework 插件在 IntelliJ IDEA 12 中不起作用

scala - 处理宏注释时无法访问父级成员

java - Java中动态多态和静态多态有什么区别?

java - 如何从 Java 父类(super class)内部调用重写方法的父类(super class)实现?