ITeye博客

ruby之二public、protected、private

gagi · 2010-06-06 10:18 · ruby · 编程语言 · Markdown

public方法,可以被定义它的类和其子类访问,可以被类和子类的实例对象调用;
protected方法,可以被定义它的类和其子类访问,不能被类和子类的实例对象直接调用,但是可以在类和子类中指定给实例对象;
private方法,可以被定义它的类和其子类访问,私有方法不能指定对象。

示例:

1、实例对象不能访问protected,private方法,但是本类之间的方法可以调用protected,private方法

class Person
  def talk
    puts "public :talk"
    speak
  end

  protected
  def speak
    puts "speak"
    laugh
  end

  private
  def laugh
    puts "private laugh"
  end

end


p1 = Person.new
p1.talk
#p1.speak 实例对象不能访问protected方法
#p1.laugh 实例对象不能访问private方法

 2、protected,private方法可以在子类的方法被调用

class Person

  protected
  def speak
    "protected:speak "
  end

  private
  def laugh
    " private:laugh"
  end

end


class Student < Person
  def useLaugh
    puts laugh
  end

  def useSpeak
    puts speak
  end
end

p2=Student.new
p2. useLaugh # private:laugh
p2. useSpeak # protected:speak

3、私有方法不能指定对象

class Person

  protected
  def speak
    "protected:speak "
  end

  private
  def laugh
    "private:laugh"
  end

  def useLaugh(another)
    puts another.laugh #这里错误,私有方法不能指定对象
  end

  def useSpeak(another)
    puts another.speak
  end

end


p1=Person.new
p2=Person.new

p2.useSpeak(p1) # protected:speak
#p2.useLaugh(p1)

评论(2)

  1. #2 楼 · mogrub · 2013-07-08 16:40

    http://tenderlovemaking.com/2012/09/07/protected-methods-and-ruby-2-0.html 这篇文章的解释还是比较清晰

  2. #1 楼 · 夜鸣猪 · 2012-02-23 05:56

    这是我看到的最清楚的解释 :idea: 明白是一回事,说清楚是另一回事 另外,public是默认,除了initialize默认private

评论功能维护中,当前仅展示历史评论。