Ruby面向对象编程详解

2019-09-25 09:48:05丽君

end

# create an object
box = Box.new(10, 20)

# let us freez this object
box.freeze
if( box.frozen? )
   puts "Box object is frozen object"
else
   puts "Box object is normal object"
end

# now try using setter methods
box.setWidth = 30
box.setHeight = 50

# use accessor methods
x = box.getWidth()
y = box.getHeight()

puts "Width of the box is : #{x}"
puts "Height of the box is : #{y}"

当上面的代码执行时,它会产生以下结果:

Box object is frozen object
test.rb:20:in `setWidth=': can't modify frozen object (TypeError)
        from test.rb:39

类常量:

可以在类里定义分配一个直接的数字或字符串值,而不使用其定义一个变量为@@ 或 @。按照规范,我们保持常量名大写。

一个常量一旦被定义就不能改变它的值,但可以在类里像常量一样直接访问,但如果要访问一个类之外的常量,那么要使用类名::常量,所示在下面的例子。

#!/usr/bin/ruby -w

# define a class
class Box
   BOX_COMPANY = "TATA Inc"
   BOXWEIGHT = 10
   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end
   # instance method
   def getArea
      @width * @height
   end
end

# create an object
box = Box.new(10, 20)

# call instance methods
a = box.getArea()
puts "Area of the box is : #{a}"
puts Box::BOX_COMPANY
puts "Box weight is: #{Box::BOXWEIGHT}"

当上面的代码执行时,它会产生以下结果:

Area of the box is : 200
TATA Inc
Box weight is: 10

类常量继承和实例方法一样,可以覆盖。

创建对象使用分配:

当创建一个对象,而不调用它的构造函数初始化,即可能有一个情况:采用 new 方法,在这种情况下可以调用分配,这将创造一个未初始化的对象,看下面的例子:

#!/usr/bin/ruby -w

# define a class
class Box
   attr_accessor :width, :height

   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end

   # instance method
   def getArea
      @width * @height
   end
end

# create an object using new
box1 = Box.new(10, 20)

# create another object using allocate
box2 = Box.allocate

# call instance method using box1
a = box1.getArea()
puts "Area of the box is : #{a}"