rudy 重载方法 详解
程序员文章站
2022-03-20 21:32:16
在子类里,我们可以通过重载父类方法来改变实体的行为. ruby> class human |&nb...
在子类里,我们可以通过重载父类方法来改变实体的行为.
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
上一篇: C++灵活易错特性-01
下一篇: lnmp之php安装