用户登录
用户注册

分享至

rudy 重载方法 详解

  • 作者: 直径无限扩张
  • 来源: 51数据库
  • 2021-07-04
在子类里,我们可以通过重载父类方法来改变实体的行为.

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   

软件
前端设计
程序设计
Java相关