[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

When to Use Protected vs. Private?

Thomas Snide

1/19/2006 9:23:00 PM

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!

--
Posted via http://www.ruby-....


4 Answers

Marco Lange

1/19/2006 9:26:00 PM

0

Hi,

> 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?

There is a subtle difference: While private fields are limited to a
single instance of a class, protected fields in an instance of a class
can be accessed from other instances of that class or its subclasses.

Regards,
Marco

dblack

1/19/2006 10:09:00 PM

0

Robert Klemme

1/20/2006 8:52:00 AM

0

Marco Lange wrote:
> Hi,
>
>> 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?
>
> There is a subtle difference: While private fields are limited to a
> single instance of a class, protected fields in an instance of a class
> can be accessed from other instances of that class or its subclasses.

AFAIK there is no such thing as "private" and "protected" fields in Ruby.
Fields are always private. You can of course access them via
instance_variables(), instance_variable_get() and _set().

You probably meant the same as David but got the wording wrong. :-)

Kind regards

robert

Marco Lange

1/22/2006 2:55:00 AM

0

Hi,

>> There is a subtle difference: While private fields are limited to a
>> single instance of a class, protected fields in an instance of a class
>> can be accessed from other instances of that class or its subclasses.
>
> AFAIK there is no such thing as "private" and "protected" fields in Ruby.
> Fields are always private. You can of course access them via
> instance_variables(), instance_variable_get() and _set().
>
> You probably meant the same as David but got the wording wrong. :-)

Yep, I meant "methods", not "fields". Dunno why I wrote "fields".

Regards,
Marco