I have two classes A
, and B
. Class B
overrides the foo
method of class A
. Class B
has a bar
method where I want to call the foo
method of the super class. What is the syntax for such a call?
class A def foo "hello" end end class B < A def foo super + " world" end def bar # how to call the `foo` method of the super class? # something similar to super.foo end end
For class methods I can call the methods up the inheritance chain by explicitly prefixing the class name. I wonder if there is a similar idiom for instance methods.
class P def self.x "x" end end class Q < P def self.x super + " x" end def self.y P.x end end
Edit My use case is general. For a specific case I know I can use alias
technique. This is a common feature in Java or C++, so I am curious to know if it is possible to do this without adding extra code.
2) super can be used to invoke parent class method The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden.
The super keyword in Java is a reference variable that is used to refer parent class objects. The super() in Java is a reference variable that is used to refer parent class constructors. super can be used to call parent class' variables and methods. super() can be used to call parent class' constructors only.
super() is implicit when no other class/superclass constructor is called.
super() returns a delegate object to a parent class, so you call the method you want directly on it: super(). area() .
In Ruby 2.2, you can use Method#super_method
now
For example:
class B < A def foo super + " world" end def bar method(:foo).super_method.call end end
Ref: https://bugs.ruby-lang.org/issues/9781#change-48164 and https://www.ruby-forum.com/topic/5356938
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