扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

Ruby中的继承怎么实现

扬州沐宇科技
2024-04-11 11:59:08
ruby

在Ruby中,实现继承主要通过定义一个类并将其设置为另一个类的子类来实现。例如:

class Animal
  def speak
    puts "I am an animal"
  end
end

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

dog = Dog.new
dog.speak  # Output: I am an animal
dog.bark   # Output: Woof!

在上面的例子中,Animal类是基类,Dog类是继承自Animal类的子类。通过在子类中定义新的方法或覆盖父类的方法,可以实现对父类的继承和扩展。

扫码添加客服微信