How to call super's super.method?

1,310 views
Skip to first unread message

Sam

unread,
Jun 5, 2012, 9:02:12 AM6/5/12
to scala...@googlegroups.com
I need override a method of super class:

class Mine extends B {

override def funcB  = {
     super.funcA
     ....
}

}

class B extends A {

override funcA = funcB

def funcB  = {
     super.funcA
}

}

class A {

def funcA = ...

}

the class A & B are not my code, so I can't modify them. But if I simply override funcB it will make StackOverflowError! my funcB code needs to call A's funcA.

Sonnenschein

unread,
Jun 5, 2012, 3:16:36 PM6/5/12
to scala-user
Sam,

afaik, you cannot bypass polymorphism meaning that you cannot have
things like super.super.x. If you don't agree with class B's
implementation of funcA, although the implementor of class B has
intentionally chosen to override funcA, you simply shouldn't extend
class B.

Peter

Dominik

unread,
Jun 6, 2012, 6:06:15 PM6/6/12
to scala...@googlegroups.com
That's not possible. If the base classes were traits instead of classes, then you could arrange the behavior you intend:

trait A {
  def funcA = println("A.funcA")
}

trait B extends A {
  override def funcA = { println("B.funcA"); funcB }
  def funcB = { println("B:funcB"); super.funcA }
}

trait Mine extends B with A {
  override def funcB = { println("Mine.funcB"); super[A].funcA }
}

If you create an instance of type Mine (val mine = new Object with Mine) and invoke funcB on it, it prints
Mine.funcB
A.funcA

But since classes A & B are not your code and given, this does not help.

Best wishes
Dominik

Josh Suereth

unread,
Jun 6, 2012, 7:00:39 PM6/6/12
to Dominik, scala...@googlegroups.com
I think you should still be able to call super[A].foo("") from a super class....   It's the invokespecial bytecode...

Dominik

unread,
Jun 7, 2012, 4:48:03 AM6/7/12
to scala...@googlegroups.com, Dominik
I thought that invokespecial can only be used to invoke only superclass, private and constructor methods, but not super-spuer-class methods. But I have to admit, that I am not a byte-code expert.
And for traits, super[T].foo is currently only allowed if T is a direct base class or trait of the current class, but since with traits code is moved around anyway, such a feature could probably be provided by the compiler, but it somehow contradicts the idea of OOP.
Dominik
Reply all
Reply to author
Forward
0 new messages