JMU
Local Classes
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Access
Common Uses
An Example
javaexamples/nested/Rectangle.java
        import java.awt.Point;

/**
 * An encapsulation of a rectangle that uses the coordinates
 * of a corner and the width and height.
 * 
 * @author  Prof. David Bernstein, James madison University
 * @version 1.0
 */
public class Rectangle 
{
  private int height, width, x, y;
  
  /**
   * Explicit Value Constructor.
   * 
   * @param x      The x-coordinate of the corner
   * @param y      The y-coordinate of the corner
   * @param width  The width
   * @param height The height
   */
  public Rectangle(int x, int y, int width, int height)
  {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
  }
  
  /**
   * Determine whether or not this Rectangle intersects 
   * the given Rectangle.
   * 
   * @param other  The other Rectangle
   * @return true if they intersect; false otherwise
   */
  public boolean intersects(Rectangle other)
  {
    /**
     * This calculation is easier to perform using the
     * coordinates of the upper-left and lower-right corners.
     * So, a local class that encapsulates rectangles in this
     * way is used.
     */
    class Rect
    {
      private Point min, max;

      /**
       * Construct a Rect from a Rectangle.
       * 
       * @param r  The Rect
       */
      public Rect(Rectangle r)
      {
        min = new Point();
        max = new Point();
        
        min.x = Math.min(r.x, r.x + r.width);
        min.y = Math.min(r.y, r.y + r.height);
        max.x = Math.max(r.x, r.x + r.width);
        max.y = Math.max(r.y, r.y + r.height);
      }
      
      /**
       * Determine whether or not this Rect intersects the given Rect.
       * 
       * @param other  The other Rect
       * @return true if they intersect; false otherwise
       */
      public boolean intersects(Rect other)
      {
        return (this.max.x >= other.min.x) && (this.min.x <= other.max.x) && 
            (this.max.y >= other.min.y) && (this.min.y <= other.max.y); 
      }
    }
    
    // Construct Rect objects from the Rectangle objects
    Rect t = new Rect(this);
    Rect o = new Rect(other);
    
    // Compare the Rect objects
    return t.intersects(o);
  }
  
}
        
An Example with an Interface
javaexamples/nested/ComparatorExample.java (Fragment: local)
            class LengthComparator implements Comparator<String>
    {
      public int compare(String a, String b)
      {
        if (a == null) a = "";
        if (b == null) b = "";
        
        if      (a.length() > b.length()) return  1;
        else if (a.length() < b.length()) return -1;
        else                              return  0;
      }
    }
    
    Arrays.sort(data, new LengthComparator());