方法重载:rudy 重载思路方法 详解

在子类里,我们可以通过重载父类思路方法来改变实体行为.
ruby> Human
| def identy
| pr "I'm a person.\n"
| end
| def train_toll(age)
| age < 12
| pr "Reduced fare.\n";
|
| pr "Normal fare.\n";
| end
| end
| end
nil
ruby> Human..identy
I'm a person.
nil
ruby> Student1<Human
| def identy
| pr "I'm a student.\n"
| end
| end
nil
ruby> Student1..identy
I'm a student.
nil

如果我们只是想增强父类 identy 思路方法而不是完全地替代它,就可以用 super.
ruby> Student2<Human
| def identy
| super
| pr "I'm a student too.\n"
| end
| end
nil
ruby> Student2..identy
I'm a human.
I'm a student too.
nil

super 也可以让我们向原有思路方法传递参数.这里有时会有两种类型人...
ruby> Dishonest<Human
| def train_toll(age)
| super(11) # we want a cheap fare.
| end
| end
nil
ruby> Dishonest..train_toll(25)
Reduced fare.
nil
ruby> Honest<Human
| def train_toll(age)
| super(age) # pass the argument we were given
| end
| end
nil
ruby> Honest..train_toll(25)
Normal fare.
nil
Tags:  什么是方法的重载 方法的重载 java方法重载 方法重载

延伸阅读

最新评论

发表评论