Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "private" modifier do?

Considering "private" is the default access modifier for class Members, why is the keyword even needed?

like image 270
Esteban Araya Avatar asked Sep 26 '08 02:09

Esteban Araya


People also ask

What is the idea of the private and public modifiers?

While the public access modifier allows a code from outside or inside the class to access the class's methods and properties, the private modifier prevents access to a class's methods or properties from any code that is outside the class.

How do I access private modifier?

Private: The private access modifier is specified using the keyword private. The methods or data members declared as private are accessible only within the class in which they are declared. Any other class of the same package will not be able to access these members.

What is a private access modifier in C++?

private Access ModifierThe private keyword is used to create private members (data and functions). The private members can only be accessed from within the class. However, friend classes and friend functions can access private members.

What is the use of private class in Java?

The private keyword is an access modifier used for attributes, methods and constructors, making them only accessible within the declared class.


2 Answers

It's for you (and future maintainers), not the compiler.

like image 22
Michael Haren Avatar answered Oct 12 '22 20:10

Michael Haren


There's a certain amount of misinformation here:

"The default access modifier is not private but internal"

Well, that depends on what you're talking about. For members of a type, it's private. For top-level types themselves, it's internal.

"Private is only the default for methods on a type"

No, it's the default for all members of a type - properties, events, fields, operators, constructors, methods, nested types and anything else I've forgotten.

"Actually, if the class or struct is not declared with an access modifier it defaults to internal"

Only for top-level types. For nested types, it's private.

Other than for restricting property access for one part but not the other, the default is basically always "as restrictive as can be."

Personally, I dither on the issue of whether to be explicit. The "pro" for using the default is that it highlights anywhere that you're making something more visible than the most restrictive level. The "pro" for explicitly specifying it is that it's more obvious to those who don't know the above rule, and it shows that you've thought about it a bit.

Eric Lippert goes with the explicit form, and I'm starting to lean that way too.

See http://csharpindepth.com/viewnote.aspx?noteid=54 for a little bit more on this.

like image 189
Jon Skeet Avatar answered Oct 12 '22 22:10

Jon Skeet