Class Inheritance

If class B inherits from class A

then instances of B have the behaviors

of both class A and class B

Inheritance Example

class Publication
  attr_accessor :publisher
end

class Magazine < Publication
  attr_accessor :editor
end

m = Magazine.new
m.publisher = "Time Inc."

m.is_a? Magazine #=> true
m.is_a? Publication #=> true
m.class == Publication #=> false

Single vs. Multiple Inheritance

A More Realistic Inheritance Example

class Rectangle
  def initialize(width, height)
    @width, @height = width, height
  end
  def area
    @width * @height
  end
end

class Square < Rectangle
  def initialize(width)
    super(width, width)
  end
end

Square.new(10).area #=> 100

A Design Note

 Previous Lesson Next Lesson 

Outline

[menu]

/