What is main purpose of declaring members as private in a class? As far as I know, we cannot access private members from outside of the class.
-
4But you can still access them from within the class.BoltClock– BoltClock2011-08-29 05:16:21 +00:00Commented Aug 29, 2011 at 5:16
-
2I think you should first read encapsulationPranay Rana– Pranay Rana2011-08-29 05:17:52 +00:00Commented Aug 29, 2011 at 5:17
-
2You should try to take a look at the basic principles of OOP. en.wikipedia.org/wiki/Object-oriented_programming and encapsulation as @Pranay Rana says.Drahakar– Drahakar2011-08-29 05:18:18 +00:00Commented Aug 29, 2011 at 5:18
-
possible duplicate of Purpose of private members in a classKirk Broadhurst– Kirk Broadhurst2011-08-29 05:24:56 +00:00Commented Aug 29, 2011 at 5:24
-
@laxman, if one of the below answers is the correct one then please mark it as answered for those people that find this question in a searchgriegs– griegs2011-08-29 05:35:08 +00:00Commented Aug 29, 2011 at 5:35
3 Answers
The point is that you don't want to expose them to the outside world. Marking them as such makes them more readable too.
eg:
public string name {get;set;}
public string emaul {get;set;}
private bool saved {get;set;}
rather than;
public string name {get;set;}
public string emaul {get;set;}
bool saved {get;set;}
Just a little easier to read.
Comments
Yes, this is the main purpose of private so that class members can't be accessible outside class. This is known as data hiding in OOP and the main purpose of this is to give owner of class ability to hide data or function so that they can only be used by functions inside class only.
1 Comment
Most C-style languages will typically provide you public, protected, and private access modifiers. This allows you to build your classes and class hierarchies and expose members on a "need to know" basis, i.e., "what mama don't know won't hurt her."
That is exactly what private access is for. If no one else needs to know about the existence of a class member, make it private and increase accessibility only as needed.