Ruby 中的继承是如何工作的?


继承是任何面向对象编程语言的关键方面。借助继承,我们可以在子类(也称为**子类**)中重用在父类(也称为**超类**)中定义的方法。

在 Ruby 中,支持单一类继承,这意味着一个类可以继承自另一个类,但它不能继承自两个超类。为了实现多重继承,Ruby 提供了一些称为**mixin**的东西,可以利用它。

继承有助于提高代码的可重用性,因为开发人员无需再次创建已为父类定义的相同方法。开发人员可以继承父类,然后调用该方法。

继承中有两个重要的术语,如下所示:

  • **超类** - 其特性被子类继承的类。

  • **子类** - 继承超类特性的类。

现在我们对 Ruby 中的继承有了一点了解,让我们举几个例子来更好地理解它是如何工作的。

示例 1

Open Compiler
# Inheritance in Ruby #!/usr/bin/ruby # Super class or parent class class TutorialsPoint # constructor of super class def initialize puts "Superclass" end # method of the superclass def super_method puts "Method of superclass" end end # subclass or derived class class Learn_Ruby < TutorialsPoint # constructor of derived class def initialize puts "Subclass" end end # creating object of superclass TutorialsPoint.new # creating object of subclass sub_obj = Learn_Ruby.new # calling superclass method sub_obj.super_method

输出

Superclass
Subclass
Method of superclass

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例 2

现在让我们再举一个例子,我们将用一点修改在子类中覆盖父类方法。

Open Compiler
# Inheritance in Ruby #!/usr/bin/ruby # Super class or parent class class TutorialsPoint # constructor of super class def initialize puts "Superclass" end # method of the superclass def super_method puts "superclass method" end end # subclass or derived class class Learn_Ruby < TutorialsPoint # constructor of derived class def super_method puts "subclass method" end end # creating object of superclass TutorialsPoint.new # creating object of subclass sub_obj = Learn_Ruby.new # calling superclass method sub_obj.super_method

输出

Superclass
Superclass
subclass method

更新于: 2022年1月25日

1K+ 次查看

启动您的 职业生涯

通过完成课程获得认证

开始
广告