Ruby/Class/super

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Call constructor from parent class

class Button
  def initialize(label)
  end
end
class StartButton < Button
  def initialize
    super("Start")       # invoke Button"s initialize
  end
  def button_pressed
    # do start actions...
  end
end
start_button = StartButton.new



To pass the color to the constructor of the base class, you use the special super method

class Animal
  def initialize(color)
    @color = color
  end
  def get_color
    return @color
  end
end
class Dog < Animal
  def initialize(color, sound)
    super(color)
    @sound = sound
  end
  def get_sound
    return @sound
  end
end
dog = Dog.new("brown", "Bark")
puts "The new dog is " + dog.get_color
puts "The new dog says: " + dog.get_sound + "" + dog.get_sound