When to Use Protected vs. Private?


#1

Can someone clarify the difference between declaring a method Protected
vs. Private?

I thought that a private method could only be accessed within the
specific defining class. However, it may also be called by subclasses.
So why the need for protected?

Thanks in advance!


#2

Hi –

On Fri, 20 Jan 2006, Thomas S. wrote:

Can someone clarify the difference between declaring a method Protected
vs. Private?

I thought that a private method could only be accessed within the
specific defining class. However, it may also be called by subclasses.
So why the need for protected?

A private method can only be called with no explicit receiver. That
means that the receiver has to be “self” – because that’s the only
time there can be no explicit receiver. (Private methods ending in
“=” do allow an explicit receiver, because they have to so that they
won’t be parsed as variable assignments.)

What protected does is to let you call a method with an explicit
receiver, as long as that receiver is of the same class is “self”.

That means you can do things like:

def compare_with(other)
self.x <=> other.x
end

even if x is protected, whereas you can’t do that from the outside
(without instance_eval or some other “invasive” technique).

David


David A. Black
removed_email_address@domain.invalid

“Ruby for Rails”, from Manning Publications, coming April 2006!