加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby类继承:如何防止公共方法在子类中被覆盖

发布时间:2020-12-17 01:27:54 所属栏目:百科 来源:网络整理
导读:是否可以防止公共方法被子类覆盖? class Parent def some_method #important stuff that should never be overwritten endendclass Child Parent def some_method #should not be possible to overwrite (raise an error if a child class tries to do it)
是否可以防止公共方法被子类覆盖?

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读