RUby学习二:类、继承

上一篇 / 下一篇  2010-08-01 11:10:45 / 个人分类:Ruby学习

一、类
class Dog          定义一个Dog类
 def speak         定义一个类的方法
   print "Bow Wow\n"
 end
end
pochi=Dog.new      创造类Dog一个实体pochi
pochi.speak        引用类的方法
运行上面程序,输出:Bow Wow
也可以创建一个临时的对象:
(Dog.new).speak
运行输出:Bow Wow
二、继承
class Mammal           创建父类
 def breathe
   print "inhale and exhale\n"
 end
end
class Cat<Mammal       创建子类,并继承父类
 def speak             子类定义自己的方法
   print "Meow\n"
 end
end
tama=Cat.new            创建子类对象
tama.breathe            引用父类的方法
tama.speak              引用子类的方法
程序输出:
inhale and exhale
Meow
三、父类的某些属性不可以被某一特定的子类继承
class Bird
 def preen
   print "i am cleaning my feathers"
 end
 def fly
   print "i am flying"
 end
end
class Penguin<Bird
  def fly
    fail "Soory,I'd rather swim."   抛出异常
  end
end

TAG:

 

评分:0

我来说两句

日历

« 2024-05-03  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 7985
  • 日志数: 13
  • 建立时间: 2010-07-24
  • 更新时间: 2010-08-19

RSS订阅

Open Toolbar