在Ruby中,繼承是通過class
關鍵字和extends
方法實現的。設計類層次結構時,需要考慮以下幾個方面:
class BaseClass
def common_method
puts "This is a common method."
end
end
class SubClass < BaseClass
def specific_method
puts "This is a specific method for SubClass."
end
end
class GrandChildClass < SubClass
def another_specific_method
puts "This is an another specific method for GrandChildClass."
end
end
Class
的類)來定義抽象方法。# 使用模塊實現接口
module Interface
def self.included(base)
base.class_eval do
def interface_method
puts "This is an interface method."
end
end
end
end
class MyClass
include Interface
end
# 使用抽象類定義抽象方法
class AbstractClass < Class
def self.abstract_method
raise NotImplementedError, "You need to implement this method."
end
end
class ConcreteClass < AbstractClass
def abstract_method
puts "This is the implementation of abstract_method for ConcreteClass."
end
end
在設計類層次結構時,還需要考慮以下幾點: