Inheritance
In this page:
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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: