Re: [問題] 請問 Ruby 有類似 Java 的 final 嗎?

看板Ruby作者 (mokuku)時間16年前 (2008/07/29 22:23), 編輯推噓1(101)
留言2則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《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

07/29 23:11, , 1F
老實講不建議這樣做,這樣喪失 ruby 重要特性之一
07/29 23:11, 1F

08/20 02:11, , 2F
Why final?
08/20 02:11, 2F
文章代碼(AID): #18ZoVEF5 (Ruby)
文章代碼(AID): #18ZoVEF5 (Ruby)