簡體   English   中英

Ruby類繼承:如何防止公共方法在子類中被覆蓋

[英]Ruby Class Inheritance: How to preven a public method from beeing overwritten in the child classes

是否可以防止公共方法被子類覆蓋?

class Parent
  def some_method
     #important stuff that should never be overwritten
  end
end

class Child < Parent
  def some_method
     #should not be possible to overwrite (raise an error if a child class tries to do it)
  end
end

謝謝!

您可以使用'method_added'和'inherited'鈎子來實現此目的:

class Foo
  def self.inherited(sub)
    sub.class_eval do
      def self.method_added(name)
        if name == :some_method
          remove_method name
          raise Exception, "Can't override #{name} method"
        end
      end
    end
  end
end

class Bar < Foo
end

class Bar
  def some_method
  end
end
# => Exception: Can't override some_method method

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM