---
title: "ruby之二public、protected、private"
author: "gagi"
date: "2010-06-06T10:18:33Z"
tags: []
categories: ["编程语言"]
slug: "ruby-public-protected-private"
draft: false
lastmod: "2010-10-27T22:00:48Z"
id: 685012
url: "https://gagi.iteye.com/blog/685012"
---

```
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)

```