Inheritance क्या है
Inheritance एक नई class को एक older class से सब कुछ receive करने देता है, एक parent से traits inherit करने वाले एक child की तरह। Child फिर अपने extras add करता है।
In this page:
Syntax
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
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
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- lowercase में
class Dog < animalइस्तेमाल करना, जो एकNameErrorहै। - child में
initializeoverride करना औरsupercall करना भूल जाना, इसलिए parent का@nameकभी set नहीं होता। - यह उम्मीद करना कि एक class कई parents से inherit करेगी, जब Ruby में single inheritance है और modules इस्तेमाल होते हैं।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: