tags:

views:

67

answers:

3

What are other purposes of private method/variable other than for protection.

A: 

For encapsulation.

Zaki
+3  A: 

Encapsulation

To hide the internal workings of an object so that it's main purpose and functionality are clearer, and easier to manipulate.

To Force Access through Accessor/Mutator Methods Only

A variable may be declared private, forcing programmers to use the accessor or mutator methods instead. These methods may perform calculations, other checks and balances, you name it. Basically, it prevents any classes from modifying this variable in a stand-alone kind of way without using it's accessor or mutator.

Deny Access In-General

As you suggested, a variable can be made private for protection, to prevent outside classes from tampering with the variable all together.

rlb.usa
Hmm, in a way, I still think that encapsulation is somewhat related to protection or privacy. You are hiding it which means you are protecting the outsiders from knowing about it at all. I am wondering whether private specifier has other purpose.
denniss
Never thought about that one though I have used it in that way for sure!
denniss
@denniss: *Information Hiding* is used as another term for encapsulation by some (compare wikipedia article).
sum1stolemyname
+1  A: 

Encapsulation is the main purpose of member scopes.

You can find a description of the reasons here:

Encapsulation is achieved by specifying which classes may use the members of an object. The result is that each object exposes to any class a certain interface — those members accessible to that class. The reason for encapsulation is to prevent clients of an interface from depending on those parts of the implementation that are likely to change in the future, thereby allowing those changes to be made more easily, that is, without changes to clients.

sum1stolemyname