在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
在设计类层次结构时,还需要考虑以下几点: