~/rubytesting/TheRubyProgrammingLanguage/Chapter7ClassesAndModules$ cat -n SubClass.rb
1 class Point
2
3 def chuchu
4 "Point: chuchu"
5 end
6
7 def chachi
8 "Point: chachi"
9 end
10
11 private :chuchu
12 protected :chachi
13 end
14
15 class SubClass < Point
16
17 def titi1
18 chuchu
19 end
20
21 def titi2
22 self.chuchu
23 end
24
25 def titi3
26 chachi
27 end
28
29 def titi4
30 self.chachi
31 end
32 end
33
34 if __FILE__ == $0
35 x = SubClass.new
36 puts x.titi1
37 begin
38 puts x.titi2
39 rescue
40 puts "Can't call private meth. via 'self'. Exception type: <#{$!.class}> message: <#{$!}>"
41 end
42
43 puts x.titi3
44
45 puts x.titi4
46
47 begin
48 puts x.chachi
49 rescue
50 puts "Can't call protected meth. from outside. Exception type: <#{$!.class}> message: <#{$!}>"
51 end
52 end
La ejecución del programa produce la salida:
~/rubytesting/TheRubyProgrammingLanguage/Chapter7ClassesAndModules$ ruby SubClass.rb Point: chuchu Can't call private meth. via 'self'. Exception type: <NoMethodError> message: <private method `chuchu' called for #<SubClass:0x1001685b8>> Point: chachi Point: chachi Can't call protected meth. from outside. Exception type: <NoMethodError> message: <protected method `chachi' called for #<SubClass:0x1001685b8>>
The rule about when a protected method can be invoked can be
described as follows:
A protected method defined by a class V (Visbility)
may be invoked on an object c
by a method in an object m (main en el ejemplo)
if and only
if the classes of c and
m
are both subclasses of the class
V.
Casiano Rodriguez León 2015-01-07