rudy 重载方法 详解
网络编程
在子类里,我们可以通过重载父类方法来改变实体的行为.
ruby> class Human
| def identify
| print "I'm a person.n"
| end
| def train_toll(age)
| if age < 12
| print "Reduced fare.n";
| else
| print "Normal fare.n";
| end
| end
| end
nil
ruby> Human.new.identify
I'm a person.
nil
ruby> class Student1<Human
| def identify
| print "I'm a student.n"
| end
| end
nil
ruby> Student1.new.identify
I'm a student.
nil
如果我们只是想增强父类的 identify 方法而不是完全地替代它,就可以用 super.
ruby> class Student2<Human
| def identify
| super
| print "I'm a student too.n"
| end
| end
nil
ruby> Student2.new.identify
I'm a human.
I'm a student too.
nil
super 也可以让我们向原有的方法传递参数.这里有时会有两种类型的人...
ruby> class Dishonest<Human
| def train_toll(age)
| super(11) # we want a cheap fare.
| end
| end
nil
ruby> Dishonest.new.train_toll(25)
Reduced fare.
nil
ruby> class Honest<Human
| def train_toll(age)
| super(age) # pass the argument we were given
| end
| end
nil
ruby> Honest.new.train_toll(25)
Normal fare.
nil
ruby> class Human
| def identify
| print "I'm a person.n"
| end
| def train_toll(age)
| if age < 12
| print "Reduced fare.n";
| else
| print "Normal fare.n";
| end
| end
| end
nil
ruby> Human.new.identify
I'm a person.
nil
ruby> class Student1<Human
| def identify
| print "I'm a student.n"
| end
| end
nil
ruby> Student1.new.identify
I'm a student.
nil
如果我们只是想增强父类的 identify 方法而不是完全地替代它,就可以用 super.
ruby> class Student2<Human
| def identify
| super
| print "I'm a student too.n"
| end
| end
nil
ruby> Student2.new.identify
I'm a human.
I'm a student too.
nil
super 也可以让我们向原有的方法传递参数.这里有时会有两种类型的人...
ruby> class Dishonest<Human
| def train_toll(age)
| super(11) # we want a cheap fare.
| end
| end
nil
ruby> Dishonest.new.train_toll(25)
Reduced fare.
nil
ruby> class Honest<Human
| def train_toll(age)
| super(age) # pass the argument we were given
| end
| end
nil
ruby> Honest.new.train_toll(25)
Normal fare.
nil
剖析 rudy 访问控制
前面,我们说Ruby没有函数,只有方法.而且实际上有不止一种方法.这一节我们介绍访问控制(accesscontrols).想想当我们在"最高层"而不是在一个类的定义里定
ruby 单态方法 分析
实体的行为取决于其类,但很多时候我们知道一个特定的实体需要特定的行为.在很多语言里,我们必须陷入另外再定义一个类的麻烦里,即使它只是用来接
ruby 模块
Ruby的模块非常类似类,除了:模块不可以有实体模块不可以有子类模块由module...end定义.实际上...模块的'模块类'是'类的类'这个类的父类.搞懂了吗?不懂?
编辑:一起学习网
标签:模块,方法,实体,子类,不可以