Java Reference
In-Depth Information
class Point {
private final int x;
private final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
void getPoint() {
System.out.println("(" + x + "," + y + ")");
}
}
Noncompliant Code Example (Public Class with Public Static Method)
This noncompliant code example again defines a class that is internal to a system and not
part of any public API. Nonetheless, this class is declared public.
Click here to view code image
public 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 + ")");
}
}
This example also complies with “OBJ01-J. Declare data members as private and
provide accessible wrapper methods” [Long 2012], untrusted code could access Point
and invoke the public static getPoint() to obtain the default coordinates. The attempt to
implement instance control using a private constructor is futile because the public static
method exposes internal class contents.
Compliant Solution (Package-Private Class)
This compliant solution reduces the accessibility of the class to package-private.
Click here to view code image
Search WWH ::




Custom Search