手机
当前位置:查字典教程网 >脚本专栏 >ruby专题 >rudy 重载方法 详解
rudy 重载方法 详解
摘要:在子类里,我们可以通过重载父类方法来改变实体的行为.ruby>classHuman|defidentify|print"I'maperson...

在子类里,我们可以通过重载父类方法来改变实体的行为.

ruby>classHuman

|defidentify

|print"I'maperson.n"

|end

|deftrain_toll(age)

|ifage<12

|print"Reducedfare.n";

|else

|print"Normalfare.n";

|end

|end

|end

nil

ruby>Human.new.identify

I'maperson.

nil

ruby>classStudent1<Human

|defidentify

|print"I'mastudent.n"

|end

|end

nil

ruby>Student1.new.identify

I'mastudent.

nil

如果我们只是想增强父类的identify方法而不是完全地替代它,就可以用super.

ruby>classStudent2<Human

|defidentify

|super

|print"I'mastudenttoo.n"

|end

|end

nil

ruby>Student2.new.identify

I'mahuman.

I'mastudenttoo.

nil

super也可以让我们向原有的方法传递参数.这里有时会有两种类型的人...

ruby>classDishonest<Human

|deftrain_toll(age)

|super(11)#wewantacheapfare.

|end

|end

nil

ruby>Dishonest.new.train_toll(25)

Reducedfare.

nil

ruby>classHonest<Human

|deftrain_toll(age)

|super(age)#passtheargumentweweregiven

|end

|end

nil

ruby>Honest.new.train_toll(25)

Normalfare.

nil

【rudy 重载方法 详解】相关文章:

Ruby面向对象编程详解

Rails link_to 详解

Ruby中钩子方法的运用实例解析

在Ruby中查找和执行方法

Ruby基础知识之方法、代码段

Ruby中case表达式详解

rudy 方法 分析

Ruby 取得指定月日期数的方法

Ruby中操作文件的方法介绍

ruby 单态方法 分析

精品推荐
分类导航