...
This noncompliant code example exposes the private (x,y)
coordinates through the getPoint()
method of the inner class. Consequently, the AnotherClass
class that belongs to the same package can also access the coordinates.
Code Block | ||
---|---|---|
| ||
class Coordinates {
private int x;
private int y;
public class Point {
public void getPoint() {
System.out.println("(" + x + "," + y + ")");
}
}
}
class AnotherClass {
public static void main(String[] args) {
Coordinates c = new Coordinates();
Coordinates.Point p = c.new Point();
p.getPoint();
}
}
|
...
Use the private access specifier to hide the inner class and all contained methods and constructors.
Code Block | ||
---|---|---|
| ||
class Coordinates {
private int x;
private int y;
private class Point {
private void getPoint() {
System.out.println("(" + x + "," + y + ")");
}
}
}
class AnotherClass {
public static void main(String[] args) {
Coordinates c = new Coordinates();
Coordinates.Point p = c.new Point(); // fails to compile
p.getPoint();
}
}
|
...
[JLS 2005] | |
| |
§2.3, Inner Classes | |
Securing Java, Getting Down to Business with Mobile Code |
...