ruby中的类变量与实例变量

上一篇 / 下一篇  2012-10-25 15:28:32 / 个人分类:ruby


类变量以@@开头,是所有子类和父类共享的
实例变量以@开头

eg.

class Person
  # 这是一个类变量,即使没有该类的对象被创建,也可以访问
  @@count = 0 
 
  def initialize(name)
  # 这是一个实例变量,每个对象可以自己单独赋值
    @name = name 
    @@count += 1
  end

  # 这是一个类方法,通过类名调用
  def self.getCount
    puts "count = #{@@count}"
  end

  # 这是一个对象方法,只能通过对象实例调用,但也可访问类变量
  def sayHi
    puts "Hi, I'm #{@name}. There are #{@@count} people."
  end
end

#Person的子类
class Student < Person
end

# 没有对象创建,通过类名访问类变量
Person.getCount
Student.getCount

p1 = Person.new("Jacky")
p1.sayHi
Person.getCount
Student.getCount

p2 = Person.new("Lily")
p2.sayHi
Person.getCount
Student.getCount

输出:
count = 0
count = 0
Hi, I'm Jacky. There are 1 people.
count = 1
count = 1
Hi, I'm Lily. There are 2 people.
count = 2
count = 2

相关阅读:

TAG: 类变量 实例变量

 

评分:0

我来说两句

Open Toolbar