进一步深入Ruby中的类与对象概念

2019-09-25 09:43:00丽君

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

Big box area is : 200

方法重载:

虽然可以在派生类中添加新的函数,但有时想改变的行为已经在父类中定义的方法。只需通过保持相同的方法名和重写该方法的功能,如下图所示,在这个例子可以这样做:

#!/usr/bin/ruby -w

# define a class
class Box
  # constructor method
  def initialize(w,h)
   @width, @height = w, h
  end
  # instance method
  def getArea
   @width * @height
  end
end

# define a subclass
class BigBox < Box

  # change existing getArea method as follows
  def getArea
   @area = @width * @height
   puts "Big box area is : #@area"
  end
end

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

# print the area using overriden method.
box.getArea()

运算符重载:

我们想“+”运算符使用+,*操作由一个标量乘以一箱的宽度和高度,这里是一个版Box类的定义及数学运算符:

class Box
 def initialize(w,h) # Initialize the width and height
  @width,@height = w, h
 end

 def +(other)     # Define + to do vector addition
  Box.new(@width + other.width, @height + other.height)
 end

 def -@        # Define unary minus to negate width and height
  Box.new(-@width, -@height)
 end

 def *(scalar)    # To perform scalar multiplication
  Box.new(@width*scalar, @height*scalar)
 end
end

冻结对象:

有时候,我们要防止被改变的对象。冻结对象的方法可以让我们做到这一点,有效地把一个对象到一个恒定。任何对象都可以被冻结通过调用Object.freeze。不得修改冻结对象:不能改变它的实例变量。

可以使用Object.frozen?语句检查一个给定的对象是否已经被冻结,被冻结的情况下的对象语句方法返回true,否则返回false值。下面的示例 freeze 的概念:

#!/usr/bin/ruby -w

# define a class
class Box
  # constructor method
  def initialize(w,h)
   @width, @height = w, h
  end

  # accessor methods
  def getWidth
   @width
  end
  def getHeight
   @height
  end

  # setter methods
  def setWidth=(value)
   @width = value
  end
  def setHeight=(value)
   @height = value
  end
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

类常量:

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