Ruby 面向对象编程:方法重写、链式调用与访问控制
在 Ruby 编程中,继承是一个强大的特性,它允许子类继承父类的属性和方法。本文将深入探讨 Ruby 中与继承相关的几个重要概念:方法重写、链式方法调用以及访问控制。
1. 方法重写(Overriding Methods)
方法重写是指子类重新定义父类中已有的方法,从而改变该方法的行为。子类从父类继承方法定义后,可以添加自己的方法定义,还能通过重写父类方法来进一步区分于父类。
class ParentClass
def this
"this"
end
end
class ChildClass < ParentClass
def this
"not this"
end
end
obj = ChildClass.new
puts obj.this
在上述代码中, ChildClass 重写了 ParentClass 的 this 方法。当创建 ChildClass 的对象并调用 this 方法时,将使用 ChildClass 中重写后的方法。
1.1 方法重写的操作步骤
为了演示方法重写的概念,我们以 Pet 和 Dog 类为例,更新这两个类,让 Pet 类实现 play
超级会员免费看
订阅专栏 解锁全文
59

被折叠的 条评论
为什么被折叠?



