在 Scala 中,如何避免在子类中重写 super.method()?
in Scala, how to avoid overriding super.method() in a subclass?
我有 3 个 类:
class B extends A {
def sup: Unit = {
super.method()
}
override def method(): Unit = {
....
}
}
object C extends B
如果我调用 C.sup(),而不是调用 A 的 method(),它将调用 B 的覆盖方法(),有没有办法避免这种行为?
我没有你描述的行为:
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
。
我有 3 个 类:
class B extends A {
def sup: Unit = {
super.method()
}
override def method(): Unit = {
....
}
}
object C extends B
如果我调用 C.sup(),而不是调用 A 的 method(),它将调用 B 的覆盖方法(),有没有办法避免这种行为?
我没有你描述的行为:
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
。