Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added placeholder for navigation script

...

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
bgColor#FFcccc

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
bgColor#ccccff

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]

§8.1.3, Inner Classes and Enclosing Instances

 

§8.3, Field Declarations

[Long 2005]

§2.3, Inner Classes

[McGraw 1999]

Securing Java, Getting Down to Business with Mobile Code

 

...

      04. Object Orientation (OBJ)