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

Inheritance क्या है

Inheritance एक नई class को एक older class से सब कुछ receive करने देता है, एक parent से traits inherit करने वाले एक child की तरह। Child फिर अपने extras add करता है।

In this page:

  1. Inheritance
Syntax
ruby
class ChildClass < ParentClass
  # inherits ParentClass methods
  def new_method
    # body
  end
end

Inheritance

एक class class Dog < Animal से दूसरी से inherit करता है, parent के सारे public और protected methods पाते हुए। यह एक "is-a" relationship model करता है, जैसे एक Dog एक तरह का Animal होना।

Ruby classes के लिए सिर्फ single inheritance support करता है -- एक class का सिर्फ एक direct superclass हो सकता है, हालाँकि modules (बाद में cover होंगे) behavior share करने का एक और तरीका देते हैं।

Note: Ruby classes के लिए सिर्फ single inheritance support करता है -- unrelated class hierarchies के आर-पार behavior share करने के लिए modules (Mixins) इस्तेमाल करें।

उदाहरण: Inheritance

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

  def eat
    puts "#{@name} is eating"
  end
end

class Dog < Animal
  def bark
    puts "#{@name} says Woof!"
  end
end

rex = Dog.new("Rex")
rex.eat
rex.bark
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. lowercase में class Dog < animal इस्तेमाल करना, जो एक NameError है।
  2. child में initialize override करना और super call करना भूल जाना, इसलिए parent का @name कभी set नहीं होता।
  3. यह उम्मीद करना कि एक class कई parents से inherit करेगी, जब Ruby में single inheritance है और modules इस्तेमाल होते हैं।
🔒

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.