How to Use Inheritance in Ruby
Inheritance is the core of object oriented programming. Building class structures makes smaller programs easy, and large programs possible. In Ruby, inheritance is used to create a relationship between classes that can be used in your code. When one class is a type of a different class, you can use inheritance to make "child classes". For example, you might have a Shape class. Making child classes of the Shape class, like a Circle or Square class, means a method that takes a Shape argument could also take a Circle as a type of shape.
Instructions
-
Use Inheritance in Ruby
-
1
Start with a base (or "super") class. The following example uses a class named Microwave:
class Microwave
def put_food_in(food)
@food = food
enddef take_food_out
food = @food
@food = nil
return food
enddef turn_on
puts "Microwave is on"
end def turn_off
puts "Microwave is off"
end
end -
2
Write an inherited class statement. This is the same as a normal class statement, but adds the "< Superclass" component. When you see "class ChildClass < Superclass", it means "class ChildClass which inherits from SuperClass." Here, inheritance is used to add a timer to the Microwave class:
class TimedMicrowave < Microwave
end -
-
3
Add new methods to the class. The class will have all of the methods of the superclass, as well any additional methods you add. You can also add new member variables and attr_* accessors:
class TimedMicrowave < Microwave
attr_reader :timerdef set_timer(seconds)
@timer = seconds
end def clear_timer
@timer = 0
end
end -
4
Override methods in the superclass with new methods. Since in the previous example a timer was added to the microwave, a turn_on method that will automatically turn the microwave off can now be implemented. Simply define a method with the same name as the method in the superclass. When it's called, the method in the child class will override the method from the superclass. Here, any code that expects to see a Microwave object can use a TimedMicrowave object:
class TimedMicrowave < Microwave
attr_reader :timerdef set_timer(seconds)
@timer = seconds
enddef clear_timer
@timer = 0
enddef turn_on
while @timer > 0
puts "Microwave is on. #{@timer} second(s) remaining."
@timer -= 1
sleep 1
end# We're done cooking, turn the microwave off
turn_off
end
end
-
1
Tips & Warnings
If you have more than one person working on a specific program, keep in mind you should not consider anything following the operator "#" as part of the code. These notes are intended to give guidance to programmers.