Fasun Lau wrote:
> irb(main):020:0>
> irb(main):021:0* class NewDemo < Demo
> irb(main):022:1> def newcall
> irb(main):023:2> newmethod + "Object ID: " + self.object_id.to_s
> irb(main):024:2> end
> irb(main):025:1>
> irb(main):026:1* protected
> irb(main):027:1> def newmethod
> irb(main):028:2> "Hello, new demo! "
> irb(main):029:2> end
> irb(main):030:1> end
> => nil
>
> irb(main):035:0> newDemo = NewDemo.new
> => #<NewDemo:0x3ae2a24>
> irb(main):036:0> newDemo.newcall
> => "Hello, new demo! Object ID: 30872850"
> irb(main):037:0> newDemo.newmethod
> NoMethodError: protected method `newmethod' called for
Your second example would have worked the same if you hadn't inherited
from Demo, so it doesn't demonstrate anything new.
Here are some examples that may prove more illustrative:
class Demo
def democall(obj)
protected_meth #d1 is calling this method
private_meth #d1 is calling this method
obj.protected_meth
obj.private_meth
end
protected
def protected_meth
puts "hello from protected_meth"
end
private
def private_meth
puts "hello from private_meth"
end
end
d1 = Demo.new
d2 = Demo.new
d1.democall(d2)
--output:--
hello from protected_meth
hello from private_meth
hello from protected_meth
r1test.rb:7:in `call': private method `private_meth' called for
#<Demo:0x24dec> (NoMethodError)
from r1test.rb:23
==========
Here is an example with some inheritance thrown in:
class Demo
protected
def protected_meth
puts "hello from protected_meth"
end
private
def private_meth
puts "hello from private_meth"
end
end
class Bird < Demo
def birdcall(obj)
protected_meth #d1 is calling this method
private_meth #d1 is calling this method
obj.protected_meth
end
end
b1 = Bird.new
b2 = Bird.new
b1.birdcall(b2)
--output:--
hello from protected_meth
hello from private_meth
hello from protected_meth
In a language like C++, private methods are not accessible in a
subclass, so the call to private_meth in Bird would cause an error.
Note that self is always the object that called the method. For
example, in this example b1 is calling the method 'call', so inside the
call method self=b1. And when methods are not called with an object
name in front of the method, the implicit caller is self. In ruby, they
call the object that is calling the method "the receiver".
--
Posted via
http://www.ruby-forum.com/.