- Forward


Anonymous Classes
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Review
Back SMYC Forward
  • Static Nested and Inner Classes:
    • Allow a class that is tightly coupled to another class to be declared and defined within it
  • Types:
    • Static nested classes - an instance of the inner class can only refer to members of the outer class using an object reference (e.g., a comparator associated with a class)
    • Inner classes - an instance of the inner class exists within an instance of the outer class and has access to its members (e.g., an iterator associated with a collection)
Review (cont.)
Back SMYC Forward
  • Local Classes:
    • A class that is defined in a block
  • Purpose:
    • Allows for the inclusion of classes that are tightly coupled to the block
Anonymous Classes
Back SMYC Forward
  • Motivation:
    • Sometimes you only need to use a local class once (i.e., in one part of the outer class) so there is no reason to name it
  • Difference from a Local Class:
    • An anonymous class is an expression (not a declaration) so it must be defined in another expression
Syntax
Back SMYC Forward
  • Similar To:
    • The invocation of a constructor
  • The Difference:
    • There is a block of code that contains a class definition
  • The Resulting Syntax:
    • The new operator
    • The name of the interface to implement or class to extend
    • Parentheses and the arguments to a construtor
    • A body containing method declarations
Syntax (cont.)
Back SMYC Forward
  • Remember:
    • The expression must be a part of a complete statement
  • Contents:
    • An anonymous class can't include any constructors
Access
Back SMYC Forward
  • Members in the Enclosing Class:
    • The anonymous class can access all members
  • Access to Local Variables:
    • The anonymous class can access all local variables that are declared to be final or (since Java v8) are effectively final
Common Uses
Back SMYC Forward
  • In General:
    • Situations in which you need an object that implements an interface or extends a class and exposing the class would cause confusion
  • In Particular - Graphical User Interfaces:
    • For subjects/listeners (in the sense of the observer pattern)
    • For models (in the sense of the model-view-controller pattern)
An Example
Back SMYC Forward
javaexamples/nested/StackTextField.java
 
An Example with an Interface
Back SMYC Forward
javaexamples/nested/ComparatorExample.java (Fragment: anonymous)
 
There's Always More to Learn
Back -