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

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

概述是否可以防止公共方法被子类覆盖? class Parent def some_method #important stuff that should never be overwritten endendclass Child < Parent def some_method #should not be possible to overwrite (rais 是否可以防止公共方法被子类覆盖?

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)  endend

谢谢!

解决方法 您可以使用’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  endendclass bar < Fooendclass bar  def some_method  endend# => Exception: Can't overrIDe some_method method
总结

以上是内存溢出为你收集整理的Ruby类继承:如何防止公共方法在子类中被覆盖全部内容,希望文章能够帮你解决Ruby类继承:如何防止公共方法在子类中被覆盖所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1222193.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存