萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Ruby 類別與物件深入解析:繼承、多型、存取器、實例方法與類別方法

Ruby 是純物件導向語言,所有事物皆為物件。本文深入探討類別定義、物件建立、initialize 建構器、實例變數、存取器(getter/setter)、實例方法、類別方法與類別變數,並提供完整可執行範例。

類別定義

class Box
  def initialize(w, h)
    @width, @height = w, h
  end
end

建立物件

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

存取器與設定器

class Box
  def initialize(w, h)
    @width, @height = w, h
  end

  # getter
  def width; @width; end
  def height; @height; end

  # setter
  def width=(val); @width = val; end
  def height=(val); @height = val; end
end

# 使用
box = Box.new(10, 20)
puts box.width   # 10
box.width = 30
puts box.width   # 30

簡寫:attr_accessor / attr_reader / attr_writer

class Box
  attr_accessor :width, :height  # 同時產生 getter/setter
  # attr_reader :width   # 唯讀
  # attr_writer :width   # 唯寫
end

實例方法

class Box
  def initialize(w, h)
    @width, @height = w, h
  end
  def area
    @width * @height
  end
end

box = Box.new(10, 20)
puts box.area  # 200

類別方法與類別變數

class Box
  @@count = 0
  def initialize(w, h)
    @width, @height = w, h
    @@count += 1
  end
  def self.count
    @@count
  end
end

Box.new(1,2); Box.new(3,4)
puts Box.count  # 2

繼承與多型

class Shape
  def area; 0; end
end

class Rectangle < Shape
  def initialize(w, h); @w, @h = w, h; end
  def area; @w * @h; end
end

class Circle < Shape
  def initialize(r); @r = r; end
  def area; Math::PI * @r**2; end
end

shapes = [Rectangle.new(10,5), Circle.new(7)]
shapes.each { |s| puts s.area }  # 多型呼叫

重點: Ruby 類別本身也是物件(Class 類別的實例),支援開放類別(隨時新增方法)、混入模組等進階特性。

copyright © 萬盛學電腦網 all rights reserved