Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select certain super class for method call in Scala

Tags:

scala

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?

like image 344
arsenbonbon Avatar asked Nov 06 '11 16:11

arsenbonbon


People also ask

How do you call a super class method?

Use of super() to access superclass constructor To explicitly call the superclass constructor from the subclass constructor, we use super() . It's a special form of the super keyword. super() can be used only inside the subclass constructor and must be the first statement.

Can we call super in method?

Only public and protected methods can be called by the super keyword. It is also used by class constructors to invoke constructors of its parent class. Super keyword are not used in static Method.

How do you call a method in Scala class?

In the basic use case, the syntax to invoke a method in an immediate parent class is the same as Java: Use super to refer to the parent class, and then provide the method name.

What does calling the super () method do?

Definition and Usage The super keyword refers to superclass (parent) objects. It is used to call superclass methods, and to access the superclass constructor. The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.


3 Answers

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"
}
like image 135
Kipton Barros Avatar answered Sep 29 '22 11:09

Kipton Barros


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.

like image 26
Matthew Farwell Avatar answered Sep 29 '22 12:09

Matthew Farwell


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

like image 29
Kim Stebel Avatar answered Sep 29 '22 13:09

Kim Stebel