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?
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.
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.
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.
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.
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"
}
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.
No. And I would leave it at that, but apparently SO wants me to go on for 30 characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With