Prev - DUP - Next - TOC

Redefinition of methods


In subclass, we get changing behavior of the instances by redefine the superclass methods. See the following example:

 ruby> class Human
 ruby|   def print_id
 ruby|     print "I'm a man-kind.\n"
 ruby|   end
 ruby|   def train_toll(age)
 ruby|     print "reduced-fare.\n" if age < 12
 ruby|   end
 ruby| end
 nil
 ruby> Human.new.print_id
 I'm a man-kind.
 nil
 ruby> class Student1<Human
 ruby|   def print_id
 ruby|     print "I'm a student.\n"
 ruby|   end
 ruby| end
 nil
 ruby> Student1.new.print_id
 I'm a student.
 nil

 ruby> class Student2<Human
 ruby|   def print_id
 ruby|     super
 ruby|     print "I'm a student too.\n"
 ruby|   end
 ruby| end
 nil
 ruby> Student2.new.print_id
 I'm a man-kind.
 I'm a studnet too.
 nil

In the redefinition, the original method of superclass can be called by `super', and the arguments of `super' are taken over to the original method if they are given.

 ruby> class Student3<Human
 ruby|   def train_toll(age)
 ruby|     super(11) # unconditionally reduced
 ruby|   end
 ruby| end
 nil
 ruby> Student3.new.train_toll(25)
 reduced-fare. 
 nil

Well, it is probably not a good example. I hope you know now how redefinitions are done.


Prev - DUP - Next - TOC