JMU
Anonymous Classes
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Review
Review (cont.)
Anonymous Classes
Syntax
Syntax (cont.)
Access
Common Uses
An Example
javaexamples/nested/StackTextField.java
        import javax.swing.*;
import javax.swing.text.*;

/**
 * A JTextField that behaves like a stack in the sense that
 * characters can only be added and removed from the "top"
 * (i.e., right side) of the String.
 *  
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 *
 */
public class StackTextField extends JTextField
{
  private static final long serialVersionUID = 1L;

  /**
   * Default Constructor.
   */
  public StackTextField()
  {
    Document model = new PlainDocument()
      /*
       * An anonymous class that overrides some methods in
       * the PlainDocument class.
       */
      {
        private static final long serialVersionUID = 1L;

        /**
         * Handle insertString messages.
         * 
         * @param offs  The offset
         * @param s     The String to insert
         * @param a     The AttributeSet describing the inserted String
         */
        public void insertString(int offs, String s, AttributeSet a)
          throws BadLocationException
        {
          if (offs == getLength()) super.insertString(offs, s, a);
        }
      
        /**
         * Handle remove messages.
         * 
         * @param offs The offset
         * @param len  The number of characters to remove
         */
        public void remove(int offs, int len)
          throws BadLocationException
        {
          if (offs + len == getLength()) super.remove(offs, len);
        }
      
      }; // Note the ; since the expression must part of a statement
    this.setDocument(model);
  }
  
}
        
An Example with an Interface
javaexamples/nested/ComparatorExample.java (Fragment: anonymous)
            Arrays.sort(data, new 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;
          }      
        });