Java Reference
In-Depth Information
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 + ")");
}
}
Accesstothe getPoint() methodisrestrictedtoclasseslocatedwithinthesamepack-
age. Untrusted code is prevented from invoking getPoint() and obtaining the coordin-
ates.
Applicability
Granting excessive access breaks encapsulation and weakens the security of Java applica-
tions.
A system with an API designed for use (and possibly extended) by third-party code
mustexposetheAPIthroughapublicinterface.ThedemandsofsuchanAPIoverridethis
guideline.
Foranygiven piece ofcode, the minimum accessibility foreach class andmember 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 private.
However, such members could be unused only because the particular body of code ex-
amined coincidentally lacks references to the members. Nevertheless, this computation
can provide a useful starting point for a programmer who wishes to minimize the access-
ibility of classes and their members.
Bibliography
[Bloch 2008]
Item 13, “Minimize the Accessibility of Classes and Members”
Item 16, “Prefer Interfaces to Abstract Classes”
[Campione 1996]
Access Control
[JLS 2013]
Search WWH ::




Custom Search