Inheritance
Inheritance lets a new class receive everything from an older class, like a child inheriting traits from a parent. The child then adds its own extras.
In this page:
Syntax
class ChildClass < ParentClass
# inherits ParentClass methods
def new_method
# body
end
end
Inheritance
A class inherits from another with class Dog < Animal, gaining all of the parent's public and protected methods. This models an "is-a" relationship, like a Dog being a kind of Animal.
Ruby only supports single inheritance for classes -- a class can have just one direct superclass, though modules (covered later) offer another way to share behavior.
Note:
Ruby supports single inheritance only for classes -- use modules (Mixins) to share behavior across unrelated class hierarchies.
Example: 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. #}
Common Mistakes
- Using
class Dog < animalin lowercase, which is aNameError. - Overriding
initializein the child and forgetting to callsuper, so the parent's@nameis never set. - Expecting a class to inherit from several parents, when Ruby has single inheritance and uses modules.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: