Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I always use the private access modifier for class fields?

Currently we are running checkstyle on our code base and it flags up any non-static class fields that don't use the private access modifier.

Is this a valid checkstyle rule, or are there situations where having non-private fields is desirable? For example, I thought the reason JUnit test cases are created in the same package was so that they could access fields using the default access modifier?

like image 492
Ricardo Gladwell Avatar asked Mar 30 '11 10:03

Ricardo Gladwell


People also ask

When should you use private access modifiers?

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.

Can we use private access modifier for class?

Private Access Modifier - PrivateClass and interfaces cannot be private. Variables that are declared private can be accessed outside the class, if public getter methods are present in the class. Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world.

Should fields always be private Java?

Fields should be declared private unless there is a good reason for not doing so. One of the guiding principles of lasting value in programming is "Minimize ripple effects by keeping secrets." When a field is private , the caller cannot usually get inappropriate direct access to the field.

Why would the access modifier private be used instead of public?

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.


1 Answers

One of the main features of object orientated programming is information hiding/encapsulation. This means a class allows access to member variables only via an interface: getter and setter methods. So other classes cannot access the member variables and modify them in an unwanted way. So the checkstyle rule is valid

like image 132
hage Avatar answered Oct 01 '22 13:10

hage