Search code examples
scalainheritancesuperclasssuper

in Scala, how to avoid overriding super.method() in a subclass?


I have 3 classes:

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

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

object C extends B

If I call C.sup(), instead of calling method() of A, it will call the overriden method() of B, is there a way to avoid this behaviour?


Solution

  • I don't have the behavior your describe:

    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
    

    As you can see, c.sup() calls A.method, not B.method.