默認即為public,全局都可以訪問,這個不解釋
private
C++, “private” 意為 “private to this class”, 但是Ruby中意為 “private to this instance”.
意思是:C++中,對于類A,只要能訪問類A,就能訪問A的對象的private方法。
Ruby中,卻不行:你只能在你本對象的實例中訪問本對象的private方法。
因為Ruby的原則是“private意為你不能指定方法接收者”,接收者只能是self,且self必須省略!
所以Ruby中子類可以訪問父類的private方法。但self.private_method是錯的。
protected
可以在本類或子類中訪問,不能在其它類中訪問。
測試代碼(public均可訪問,代碼略)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
class A def test protected_mth private_mth self .protected_mth #self.private_mth #wrong obj = B . new obj.protected_mth #obj.private_mth #wrong end protected def protected_mth puts "#{self.class}-protected" end private def private_mth puts "#{self.class}-private" end end class B < A def test protected_mth private_mth self .protected_mth #self.private_mth #wrong obj = B . new obj.protected_mth #obj.private_mth #wrong end end class C def test a = A . new #a.protected_mth #wrong #a.private_mth #wrong end end A . new .test B . new .test C . new .test |
注:ruby的訪問控制不同于java,沒有包的區別。
其它包中的類只要引用目標類,和目標類同包下類訪問控制規則相同。