What is the use of super?

Questions by sripri   answers by sripri

Showing Answers 1 - 9 of 9 Answers

Santhiya

  • Aug 8th, 2007
 

Use the super keyword to call the superclass implementation of the current method.

Satya

  • Mar 11th, 2013
 

Super is used to call the parent classes initialize method from the childs initialize method. super has following forms of implementation.
1. Calling only the super means, call the parents initialize method by passing all the parameters passed to childs initialize method that are passed when new is called.

2. Calling the super with brackets i.e., super(), calls the parents initialize method by not passing any parameters.

3. Calling super(x, y) with specific arguments, calls the parents initialize method by passing parameters that are needed from the childs initialize method. The order and no. of parameters passed is maintained. see examples

Code
  1. class Parent

  2.         def initialize

  3.          ........

  4.         end

  5. end

  6.  

  7. class Child < Parent

  8.         def initialize

  9.                 super

  10.                 .....

  11.         end

  12. end

  13.  

  14. The above super essentially passes all the arguments passed by Child#initialize to Parent#initialize.

  15.  

  16. 2. If childs initialize method takes some parameters and parents initialize doesnt then use super() instead of just super.

  17.  

  18. class Parent

  19.         def initialize

  20.          .........

  21.         end

  22. end

  23.  

  24. class Child < Parent

  25.         def initialize(foo)

  26.                 super()

  27.                 ......

  28.         end

  29. end

  30.  

  31. The above super() essentially doesnt pass any argument to the Parent#initialize from Child#initialize

  32.  

  33. 3. If childs initialize method takes some parameters and parents initialize also needs parameters then follow the example:

  34.  

  35. class Parent

  36.         def initialize(x)

  37.                 ......

  38.         end

  39. end

  40.  

  41. class Child < Parent

  42.         def initialize(x, y)

  43.                 super(x)

  44.                 .............

  45.         end

  46. end

  Was this answer useful?  Yes

Venus Jain

  • Aug 22nd, 2017
 

To call the method from Parent class

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions