Ruby-继承

来自站长百科
跳转至: 导航、​ 搜索

导航: 上一页 | ASP | PHP | JSP | HTML | CSS | XHTML | aJAX | Ruby | JAVA | XML | Python | ColdFusion

在Ruby里,我们可以这样表述这一概念:

ruby> class Mammal
| def breathe
| print "inhale and exhale\n"
| end
| end
nil
ruby> class Cat<Mammal
| def speak
| print "Meow\n"
| end
| end
nil


虽然我们并未指明一只猫要怎样呼吸,但因为Cat是定义为Mammal的子类的(在OO术语里,较小的类叫子类,相比较大的类称父类),每一只猫都将继承来自于Mammal类的行为.因此从程序员的角度出发,猫天生就拥有呼吸这一能力;当我们加上speak方法后,我们的猫就能呼吸,也可以发声了.

ruby> tama = Cat.new
#<Cat:0xbd80e8>
ruby> tama.breathe
inhale and exhale
nil
ruby> tama.speak
Meow
nil


也会遇到这样的情况:父类的某些属性不可以被某一特定的子类继承.虽然一般鸟类都会飞,但企鹅是鸟类中不会飞的一个子类.

ruby> class Bird
| def preen
| print "I am cleaning my feathers."
| end
| def fly
| print "I am flying."
| end
| end
nil
ruby> class Penguin<Bird
| def fly
| fail "Sorry. I'd rather swim."
| end
| end
nil


抛开脑尽力疲地为每一个新类定义属性,我们只需要新增或重定义子类和父类之间的区别.继承的这一用法有时也叫做特点编程(differential programming).这是面向对象编程的又一好处.