You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

"An inner class is a nested class that is not explicitly or implicitly declared static." JLS 8.1.3

Inner class usage is prone to error unless the semantics are well understood. A common notion is that only the outer class can access the contents of the nested inner class(es). Not only does the inner class have access to the private fields of the outer class, the same fields can be accessed by another class in the package depending on whether the inner class is declared public or if it contains public methods/constructors.

Non-Compliant Code Example

The code in this non-compliant example illegally exposes the (x,y) coordinates through the getPoint() method of the inner class. The AnotherClass class can thus illegally access the coordinates which is clearly not desired.

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();
  }        
}

Compliant Solution

Use the private access specifier for declaring the inner class(es) and all contained methods and constructors.

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();
    p.getPoint();
  }        
}

References

JLS, 8.1.3 Inner Classes and Enclosing Instances http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.1.3
Securing Java, Gary McGraw

  • No labels