Ruby面向对象编程详解

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

      @width
   end
   def getHeight
      @height
   end
   # make them private
   private :getWidth, :getHeight

   # instance method to print area
   def printArea
      @area = getWidth() * getHeight
      puts "Big box area is : #@area"
   end
   # make it protected
   protected :printArea
end

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

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

# try to call protected or methods
box.printArea()

当上面的代码被执行时,产生下面的结果。在这里,第一种方法被调用成功,但第二种方法给一个提示。

Area of the box is : 200
test.rb:42: protected method `printArea' called for #
<Box:0xb7f11280 @height=20, @width=10> (NoMethodError)

类的继承:

在面向对象的编程中最重要的概念之一是继承。继承允许我们定义一个类在另一个类的项目,这使得它更容易创建和维护应用程序。

继承也提供了一个机会,重用代码的功能和快速的实现时间,但不幸的是Ruby不支持多级的继承,但Ruby支持混入。一个mixin继承多重继承,只有接口部分像一个专门的实现。

当创建一个类,而不是写入新的数据成员和成员函数,程序员可以指定新的类继承现有类的成员。这种现有的类称为基类或父类和新类称为派生类或子类。

Ruby也支持继承。继承和下面的例子解释了这个概念。扩展类的语法很简单。只需添加一个<字符的超类声明的名称。例如,定义Box类的子类classBigBox:

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

   # add a new instance method
   def printArea
      @area = @width * @height
      puts "Big box area is : #@area"
   end
end

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

# print the area
box.printArea()

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

Big box area is : 200

方法重载:

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