Inheritance

Optional Node
Premium Content - Free Preview

Inheritance lets you create child classes that inherit methods (and variables) from parent classes. See this page on Inheritance for a quick overview of the concepts involved.

Inheritance

Use < after a class name to make it inherit from another class. For example, Dog inherits from Animal which inherits from LifeForm:

class LifeForm    
  def initialize
    @size = 1
  end

  def size
    @size
  end

  def grow
    @size += 1
  end    
end

class Animal < LifeForm
  def move
    puts "Moved.."
  end
end

class Dog < Animal
  def bark
    puts "Woof!"
  end
end

Any dog you create will now inherit the methods from all its superclasses. (The output is shown after #=>).

dog = Dog.new
dog.move  #=> Moved..
puts dog.size #=> 1
dog.grow  
puts dog.size   #=> 2

Challenge

Until now, everything we've created has been focused around storing and retrieving products. But we may want to store other data, such as users or comments. It would be redundant to re-write an entire Database, Controller and Router for each new type. Instead, let's refactor the code so common functionality of the Controller and Database can be shared by many different categories.


End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Contact Us