Ruby面向对象编程详解

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


#!/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