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


繼承是任何面向物件程式語言的關鍵方面。藉助繼承,我們可以在子類(也稱為**子類**)中重用在父類(也稱為**超類**)中定義的方法。

在 Ruby 中,支援單一類繼承,這意味著一個類可以繼承自另一個類,但它不能繼承自兩個超類。為了實現多重繼承,Ruby 提供了一些稱為**mixin**的東西,可以利用它。

繼承有助於提高程式碼的可重用性,因為開發人員無需再次建立已為父類定義的相同方法。開發人員可以繼承父類,然後呼叫該方法。

繼承中有兩個重要的術語,如下所示:

  • **超類** - 其特性被子類繼承的類。

  • **子類** - 繼承超類特性的類。

現在我們對 Ruby 中的繼承有了一點了解,讓我們舉幾個例子來更好地理解它是如何工作的。

示例 1

# 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

示例 2

現在讓我們再舉一個例子,我們將用一點修改在子類中覆蓋父類方法。

# 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+ 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.