← Back to Ruby Course | Chapter 9: OOP | Lesson 6 of 7

super क्या है

super एक child class को same method का parent का version call करने देता है, एक parent से पूछने की तरह कि उन्होंने इसे पहले कैसे किया। आप फिर अपना हिस्सा add कर सकते हैं।

In this page:

  1. super
Syntax
ruby
class ChildClass < ParentClass
  def method_name(param)
    super          # or super(param)
    # extra behavior
  end
end

super

super एक overriding method के अंदर से parent class पर same-named method call करता है, आपको parent का behavior पूरी तरह replace करने की बजाय extend करने देते हुए।

बिना parentheses के super call करना automatically current method के सारे arguments forward करता है; empty parentheses वाला super() parent method को बिल्कुल बिना arguments के call करता है। Careful न होने पर यह distinction subtle bugs का एक common source है।

Warning:
  • super (बिना parens) automatically current arguments forward करता है।
  • super() (empty parens) parent method को बिना arguments के call करता है -- ये same नहीं हैं।

उदाहरण: super

markup
class Animal
  def initialize(name)
    @name = name
  end

  def describe
    puts "I am #{@name}"
  end
end

class Dog < Animal
  def initialize(name)
    super(name)
  end

  def describe
    super
    puts "...and I am a dog"
  end
end

rex = Dog.new("Rex")
rex.describe
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. बिना parentheses के super call करना और कोई arguments न होने की उम्मीद करना, जब यह automatically current arguments pass करता है; कोई न होने के लिए super() इस्तेमाल करें।
  2. initialize में super भूल जाना, इसलिए parent का setup skip हो जाता है।
  3. एक ऐसे method में super इस्तेमाल करना जिसका कोई parent version न हो, जो NoMethodError raise करता है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.