Ruby面向对象

Ruby面向对象

​ Ruby是真正的面向对象语言,一切皆为对象,甚至基本数据类型都是对象

基本用法

class Box
  # 构造函数
  def initialize(w,h)
    @with, @height = w, h #加@的是实例变量
  end
  # get方法
  def getWidth
    @with # 默认最后一条语句的返回值作为函数返回值
  end
  def getHeight
    @height
  end
  # set方法
  def setWidth(w)
    @with = w
  end
  # 实例方法
  def getArea
    @with * @height
  end
end

box = Box.new(10, 20)
box.setWidth 15
puts box.getWidth
puts box.getHeight
puts box.getArea

简化get,set

​ Ruby中,实例变量前面要加@,外部无法直接读写,要自己写get,set方法来访问。Ruby提供了一种方便的属性声明方法来更方便地做访问控制:

class Box
  # 声明外部可读,要用符号类型
  attr_reader :label
  # 声明外部可写
  attr_writer :width, :height
  def initialize(w,h,label)
    @width, @height = w, h
    @label = label
  end
  def getArea
    @width * @height,
  end
end

box = Box.new(10, 20,'box')
puts box.label
box.width = 15
puts box.getArea

​ attr_accessor声明相当于reader+writer

类变量&类变量

​ 类变量前面加上@@就可以,类方法只要前面加上self即可

class Box
  # 初始化类变量
  @@count = 0
  def initialize(w,h)
    @width, @height = w, h
    @@count += 1
  end
  # 类方法
  def self.printCount
    puts "Box count is #{@@count}"
  end
end

box1 = Box.new(10, 20)
box2 = Box.new(15, 20)
Box.printCount

方法访问控制

​ 我们经常会对类做一些封装,因此访问控制还是必要的。Ruby的成员变量的访问控制在前面用get、set访问控制已经解决。方法的控制有三个级别:

  • public:默认情况下,除了initialize方法是private,其他都是public的
  • private:只有类内可以访问
  • protected:可以在类内和子类中使用

举例

class Box
  def initialize(w,h)
    @width, @height = w, h
  end
  def getArea
    caculate
    @area
  end
  def caculate
    @area = @width * @height
  end
  # 方法的权限控制声明
  private :caculate
end

box = Box.new(10, 20)
puts box.getArea

继承

# 定义基类
class Box
  def initialize(w,h)
    @width, @height = w, h
  end
  def getArea
    @width*@height
  end
end

# 定义子类
class BigBox < Box
  def printArea
    # 继承基类方法和变量
    puts getArea
  end
end

box = BigBox.new(10,20)
box.printArea

方法重载&运算符重载

class Box
  attr_reader :width, :height
  def initialize(w,h)
    @width, @height = w,h
  end
  def getArea
    @width*@height
  end
end

class BigBox < Box
  # 重载方法
  def getArea
    @area = @width * @height
    puts "Big box area is: #{@area}"
  end
  # 运算符重载
  def +(other)         # 定义 + 来执行向量加法
    BigBox.new(@width + other.width, @height + other.height)
  end
end
box1 = BigBox.new(10,20)
box2 = BigBox.new(5,10)
box1.getArea
box3 = box1+box2
box3.getArea

小结

​ Ruby中的面向对象应该说非常简洁优雅,不愧是纯粹的面向对象语言。

原文地址:https://www.cnblogs.com/fanghao/p/7884175.html