看板 Ruby 關於我們 聯絡資訊
※ 引述《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
godfat:老實講不建議這樣做,這樣喪失 ruby 重要特性之一 07/29 23:11
zusocfc:Why final? 08/20 02:11