继承

继承 #

Ruby 中使用 < 表示继承关系。

class Button < View

继承后可以通过 super() 调用父类的函数,如果当前类和父类的函数参数相同时可以省略括号和参数列表。

class View
  attr_reader :width
  attr_reader :height

  def initialize(width, height)
    @width = width
    @height = height
  end

  def desc(prefix)
    "#{prefix} width = #{@width}, height = #{@height}"
  end
end

class Button < View
  attr_writer :name
  attr_accessor :width

  def initialize(width, height, name)
    super(width, height)
    @name = name
  end

  def desc(prefix)
    super << " ,name = #{@name}"
  end
end

button = Button.new(480, 360, 'Simple Click')
puts button.desc(' =>')

如果父类初始化函数含有参数时,子类省略初始化函数时则必须传入满足父类的参数列表,如果子类也定义了初始化函数则无法满足父类的参数列表,多余的值会被赋予空值。

class ViewGroup < View
  def initialize
  end
end

view_group = ViewGroup.new
puts view_group.desc ' => '
沪ICP备17055033号-2