How can I call parents constructor ?
module C attr_accessor :c, :cc def initialization c, cc @c, @cc = c, cc end end class B attr_accessor :b, :bb def initialization b, bb @b, @bb = b, bb end end class A < B include C attr_accessor :a, :aa def initialization (a, b, c, aa, bb, cc) #call B::initialization - ? #call C::initialization - ? @a, @aa = a, aa end end
Thanks.
In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private). $obj = new OtherSubClass();
In Ruby, constructors are invoked with the help of "new" keyword and a new keyword is used for creating an object of the class. The "new" keywords give an internal call to the "initialize" method and if the new has got some arguments specified, it will be passed to the initialize method.
super() can be used to invoke immediate parent class constructor.
Ruby uses the super keyword to call the superclass implementation of the current method. Within the body of a method, calls to super acts just like a call to that original method. The search for a method body starts in the superclass of the object that was found to contain the original method.
Ruby doesn't have constructors, therefore it's obviously not possible to call them, parent or otherwise. Ruby does have methods, however, and in order to call the parent's method with the same name as the currently executing method, you can use the super
keyword. [Note: super
without arguments is a shortcut for passing the same arguments that were passed into the currently executing method. If you actually want to pass no arguments, you have to do so explicitly: super()
.]
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