作者mokuku (mokuku)
看板Ruby
标题Re: [问题] 请问 Ruby 有类似 Java 的 final 吗?
时间Tue Jul 29 22:23:09 2008
※ 引述《mokuku (mokuku)》之铭言:
: Java 语法里面, 可以用
: class Test
: {
: public final void test_function() {}
: }
: 这样的定义,
: 让 Test 的子类别无法重新定义 test_function() 这个 method,
: 即 如果 Test 子类别尝试
: class SubTest extends Test
: {
: public final void test_function() {}
: }
: 会发生
: test_function() in SubTest cannot override
: test_function() in Test; overridden method is final
: 这样的错误!
: 请问 Ruby 里有类似的语法吗?
: 谢谢!
找到别人写的解法
http://www.thesorensens.org
/2006/10/06/final-methods-in-ruby-prevent-method-override
文章中提供的 Code 如下:
class Object
@@final_methods = {}
class << self
def prevent_override?(method_name)
@@final_methods.each do |class_name, final_methods|
ancestors = self.ancestors
ancestors.shift # remove myself from the list
if ancestors.include?(class_name) and
final_methods.include?(method_name)
raise "Child class '#{self}' should not override parent class method '#{class_name}.#{method_name}'."
end
end
end
def method_added(method_name)
prevent_override?(method_name)
end
def final(*names)
@@final_methods[self] = names
end
end
end
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 221.169.208.119
1F:推 godfat:老实讲不建议这样做,这样丧失 ruby 重要特性之一 07/29 23:11
2F:→ zusocfc:Why final? 08/20 02:11