我怎样才能让孩子忽略父母认为有趣的事情而直接去祖父母认为有趣的事情呢?
孩子仍然继承自父母,但它只是不同意一些方法。
调用超类的超类的方法?
另外,如果我处于孩子不同意父母的意见但同意父母的父母的情况,这是否被认为是糟糕的设计?
class Grandparent
def fun
#do stuff
end
end
class Parent < Grandparent
def fun
super
#parent does some stuff
end
def new_business
#unrelated to my parent
end
end
class Child < Parent
def fun
super
#child also does some stuff
end
def inherit_new_business
new_business
#stuff
end
end
在 Ruby 中,通过组合而不是继承来获得这种行为通常更容易。为了实现这一点Modules
包含您希望类具有的特定行为。
但如果你绝对必须使用继承,你可以这样做:
class Child < Parent
def fun
GrandParent.instance_method(:fun).bind(self).call
# fun child stuff
end
end
这将完全按照它所说的进行。获取实例方法fun
从 GrandParent 类中,将其附加到当前实例对象self
并调用它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)