Anonymous Classes
In order to reduce the verbosity of the language, Java allows anonymous classes
to be instantiated with the new keyword. For example,
every button in a Swing
application has an ActionListener that is invoked when the button
is clicked. Rather than create a new class file for every action, you could instead
declare anonymous classes that implement the ActionListener interface.
Anonymous classes provide support for closures.
A closure is a block of code
that can be passed around while maintaining access to variables of the enclosing
scope. For example, a button that changes the title of a Swing application would
need a closure to access the window frame. Although it may appear that
anonymous classes have direct
access to enclosing variables, in fact the variables
are copied in the same manner as method arguments (
pass-by-value). In order
to prevent ambiguity, all enclosing variables must
be declared final before
they can be accessed by an anonymous class.
Java 8 provides even more succinct support for closures in the form of lambda
expressions. A lambda expression is a single-line representation of an
anonymous class that contains a single method.
Exceptions
Exceptions are special objects that are thrown whenever an error interrupts the
normal execution of code. All exceptions are descendents of the Throwable
class and are divided into two categories: unchecked
exceptions and checked
exceptions.