当前位置: 移动技术网 > IT编程>脚本编程>Ruby > rudy 重载方法 详解

rudy 重载方法 详解

2017年12月12日  | 移动技术网IT编程  | 我要评论
在子类里,我们可以通过重载父类方法来改变实体的行为.

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   

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网