...
Classes and class members should be given minimum possible access so that malicious code has the least chance of compromising their security. As far as possible, sensitive classes should avoid exposing internal functionality through interfaces because interfaces allow only public methods, and such methods carry forward to the public Application Programming Interface (API) of the class. An exception is implementing an unmodifiable interface that exposes a public immutable view of a mutable object (SEC14-J. Provide sensitive mutable classes with unmodifiable wrappers). Additionally, note that even if a non-final class's visibility is default, it can be susceptible to misuse if it contains public methods.
If a class, interface, method or field is part of a published Application Programming Interface (API) such as a web service end point, it may be declared public. If not, it should be declared either package-private, protected or private. For example, classes are encouraged to provide public static factories to implement instance control with a private constructor provided the class is not security critical.
Noncompliant Code Example (Public Class)
...
| Code Block | ||
|---|---|---|
| ||
final class Point {
private static final int x = 1;
private static final int y = 2;
private Point(int x, int y) {}
public static void getPoint() {
System.out.println("(" + x + "," + y + ")");
}
}
|
Exceptions
...
Risk Assessment
Granting unnecessary access breaks encapsulation and weakens the security of Java applications.
...