ruby access control(public,protected,private)

public methods

public methods 可以被所有人訪問,他沒有訪問控制, note: 方法默認是public的,(除了initialize方法,它總是私有的)


protected methods

protected methods 只能被(定義方法的類或者它的子類)的對象調用,並且 訪問只能在(定義方法的類或者它的子類)進行。


private methods

private methods 不能被明確的(explicit)接收者(receiver)調用,它的接收者總是當前對象(self),這說明私有方法只能在當前對象的上下文環境被調用,你不能調用其他對象的私有方法

  #第一種寫法
  class MyClass
    def method_1  #default public
    end

    private     #下面的方法都是私有的
    def method_2
    end
    def method_3
    end

    protected   #下面的方法都是保護方法
    def method_4
    end
  end
  #第二種寫法
  class MyClass
    def method_1
    end
    def method_2
    end
    def method_3
    end

    public  :method_2
    protect :method_1
    private :method_3
  end

example

class Account
  attr_accessor :balance
  def initialize(balance)
    @balance = balance
  end
end

class Transaction
  def initialize(outer,incomer)
    @outer = outer
    @incomer = incomer
  end
  def traning(count)
    out(count)
    income(count)
  end
  private
  def out(count)
    @outer.balance -= count 
  end
  def income(count)
    @incomer.balance += count
  end
end

account_1 = Account.new(100)
account_2 = Account.new(200)
trans = Transaction.new(account_1,account_2)
trans.traning(50)
p "account_1: #{account_1.balance}, account_2: #{account_2.balance} "
#=> account_1: 50, account_2: 250
發佈了35 篇原創文章 · 獲贊 2 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章