在Scala中,如何避免在子类中覆盖super.method()?

时间:2015-09-27 21:04:04

标签: scala inheritance superclass super

我有3个班级:

class B extends A {
  def sup: Unit = {
    super.method()
  }

  override def method(): Unit = {
  ....
  }
}

object C extends B

如果我调用C.sup(),而不是调用A的method(),它将调用B的overriden方法(),有没有办法避免这种行为?

1 个答案:

答案 0 :(得分:3)

我没有你所描述的行为:

C:\...>scala
Welcome to Scala version 2.11.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_60).
Type in expressions to have them evaluated.
Type :help for more information.

scala> :paste
// Entering paste mode (ctrl-D to finish)

class A {
  def method(): Unit = println("A.method")
}

class B extends A {
  def sup(): Unit = super.method()
  override def method(): Unit = println("B.method")
}

class C extends B

// Exiting paste mode, now interpreting.

defined class A
defined class B
defined class C

scala> val c = new C
c: C = C@62833051

scala> c.sup()
A.method

如您所见,c.sup()拨打A.method,而不是B.method