如果我们只是想增强父类的方法,而不是完全地替代它,就可以用关键字super指明。看程序 E6.2-1.rb :Person类的talk方法只是报告姓名。 Student类的talk方法用super来调用Person类的talk方法,报告姓名;随后又加上了一条语句,来表明身份。
ruby 代码
- #E6.2-1.rb
- class Person
- def talk(name)
- print "my name is #{name}."
- end
- end
- class Student < Person
- def talk(name)
- super
- print "and I'm a student.\n"
- end
- end
- aPerson=Person.new
- aPerson.talk("kaichuan") # => my name is kaichuan.
- print "\n\n"
- aStudent=Student.new
- aStudent.talk("kaichuan") # => my name is kaichuan.and I'm a student.
完整阅读,请看我写的 Ruby语言中文教程all in one