热门关键字:  ubuntu  分区  函数  linux系统进程  Fedora

当前位置 :| 主页>Linux教程>编程开发>Ruby>

Ruby On Rails入门经典 第三章 类和对象

来源: 作者: 时间:2007-11-07 Tag: 点击:
创建类:
class Animal
end
 
class Animal
  def initialize
    @color = "red"
  end
 
  def get_color
    return @color
  end
end
@color是实例变量,实例变量用于在对象中保存对象
 
创建对象:
animal = Animal.new
puts "The new animal is " + animal.get_color
new调用了 initialize方法创建对象
 
把上面的initialize改为:
def initialize(color)
  @color = color
end
则调用变为: animal = Animal.new("brown")
 
ruby的属性:
可读属性:
attr_reader:color
可写属性:
atter_writer:color
可读写属性:
attr_accessor
 
继承类:
class Dog < Animal
  def initialize(color, sound)
    super(color)
    ..
  end
end
Dog继承了父类的构造函数,使用super函数调用
同时,get_color方法也继承了,因为ruby默认就是public的,而不是private的。
 
重写方法,相当于覆盖:
class Dog < Animal
  ...
  def get_color
    return "blue"
  end
end
则会覆盖了父类Animal的get_color方法
 
类变量:
@@前缀创建类变量,类的所有实例共享一个类变量
class Animal
  @@number_animals = 0;
  def initialize(color)
    @color = color
    @@number_animals += 1
  end
 
  def get_number_animals
    return @@number_animals
  end
end
 
类方法:
只需要类名就可以调用的方法,只能使用类变量
class Mathematics
  def Mathematics.add(operand_one, operand_two)
    return operand_one + operand_two
  end
end
上一篇:没有了
下一篇:没有了
最新评论共有 4 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名?
注册