...
The following table presents a simplified view of the access control rules. An x indicates that the particular access is permitted from within that domain. For example, an x in the class column means that the member is accessible to code present within the same class in which it is declared. Similarly, the package column indicates that the member is accessible from any class (or subclass) defined in the same package, provided that the class (or subclass) is loaded by the class loader that loaded the class containing the member. The same class loader condition applies only to package-private member access.
Access Specifier | Class | Package | Subclass | World |
---|---|---|---|---|
| x |
None | x | x | x* |
---|
| x | x | x** |
---|
| x | x | x | x |
---|
* Subclasses within the same package can also access members that lack access specifiers (default or package-private visibility). An additional requirement for access is that the subclasses must be loaded by the class loader that loaded the class containing the package-private members. Subclasses in a different package cannot access such package-private members.
...
For any given piece of code, the minimum accessibility for each class and member can be computed so as to avoid introducing compilation errors. A limitation is that the result of this computation may lack any resemblance to what the programmer intended when the code was written. For example, unused members can obviously be declared to be private. However, such members could be unused only because the particular body of code examined coincidentally lacks references to the members. Nevertheless, this computation can provide a useful starting point for a programmer who wishes to minimize the accessibility of classes and their members.
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Parasoft Jtest |
| CERT.OBJ51.DPAF | Declare package-private fields as inaccessible as possible Declare package-private methods as inaccessible as possible Declare "package-private" types as inaccessible as possible Declare "public/protected" types as inaccessible as possible Declare "public/protected" fields as inaccessible as possible Declare "public/protected" methods as inaccessible as possible |
Bibliography
Item 13, "Minimize the Accessibility of Classes and Members" | |
[JLS 2014] | |
Chapter 3, "Java Language Security Constructs" |
...
...