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

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

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

String representation of box is : (w:10,h:20)

访问控制:

Ruby提供了三个级别的保护实例方法的级别:public, private 和 protected。 Ruby没有应用实例和类变量的任何访问控制权。

        Public Methods: 任何人都可以被称为public方法。方法默认为公用初始化,这始终是 private 除外。 .     Private Methods: private方法不能被访问,或者甚至从类的外部浏览。只有类方法可以访问私有成员。     Protected Methods: 受保护的方法可以被调用,只能通过定义类及其子类的对象。访问保存在类内部。

以下是一个简单的例子来说明三个访问修饰符的语法:

#!/usr/bin/ruby -w

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

  # instance method by default it is public
  def getArea
   getWidth() * getHeight
  end

  # define private accessor methods
  def getWidth
   @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()