作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
是否可以防止公共(public)方法在子类中被覆盖?
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” Hook :
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
关于Ruby 类继承 : How to preven a public method from beeing overwritten in the child classes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7834760/
是否可以防止公共(public)方法在子类中被覆盖? class Parent def some_method #important stuff that should never be
我是一名优秀的程序员,十分优秀!