9

If I have a class constellation in Scala like this:

class A {
def foo() = "bar"
}

class B extends A {
override def foo() = "BAR"
}

class C extends B {
}

is it possible in class C to explicitly call the method foo that was defined in A?

arsenbonbon
  • 748
  • 9
  • 22

3 Answers3

18

No, but you can do something similar with multiple trait inheritance:

trait A { def foo = "from A" }

class B extends A { override def foo = "from B" }

class C extends B with A {
  val b = foo          // "from B"
  val a = super[A].foo // "from A"
}
Kipton Barros
  • 21,002
  • 4
  • 67
  • 80
  • And why this does not violate encapsulation as @Matthew said in his answer? – MaxNevermind Jan 15 '17 at 06:45
  • 1
    In this example, class `C` explicitly extends `A`, so it gets direct access `A`'s behavior. To be honest, this example looks odd, and I'm not sure it's good style. – Kipton Barros Feb 23 '17 at 23:35
8

No, you can't, because it violates encapsulation. You are bypassing your parents behaviour, so C is supposed to extend B, but you are bypassing this.

Please see Jon Skeets excellent answer to the same question Why is super.super.method(); not allowed in Java?.

Please note that you can access the field by reflection, but you don't want to do that.

Community
  • 1
  • 1
Matthew Farwell
  • 60,889
  • 18
  • 128
  • 171
2

No. And I would leave it at that, but apparently SO wants me to go on for 30 characters.

Kim Stebel
  • 41,826
  • 12
  • 125
  • 142
  • 13
    If you happen to know the reason why this is not possible, that could be something to fill up the 30 Characters :) – arsenbonbon Nov 06 '11 at 17:56