Inner Classes and Other New Language Features

Contents:
An Overview of Inner Classes
Nested Top-Level Classes and Interfaces
Member Classes
Local Classes
Anonymous Classes
Other New Features of Java 1.1

The largest enhancement to the Java language in Java 1.1 is something called "inner classes." With this addition to the language, classes can be defined as members of other classes, just as fields and methods can be defined within classes. Classes can also be defined within a block of Java code, just as local variables can be defined within a block of code.

From one point of view, the addition of inner classes regularizes the syntax of Java. From another point of view, though, inner classes create quite a few special cases, and a confusing array of new rules. In practice, however, if you avoid the obscure and pathological cases, inner classes prove to be an elegant and extremely useful addition to the language. Their use is particularly common in conjunction with the new event model defined by the AWT in Java 1.1.

An Overview of Inner Classes

Java 1.0 allowed classes and interfaces to be defined in exactly one context: at the "top level," as members of packages. Java 1.1 adds one new type of top-level classes and interfaces, and adds three new types of "inner classes," as outlined below. Later sections of this chapter describe each of these new types of classes and interfaces in more detail and present examples of their use.

Table 5.1 summarizes the types of classes and interfaces that can be defined in Java 1.1; the remaining sections of the chapter document each type in more detail.

Inner Class Summary
Class Type Description

Top-level classes and interfaces

Package member class or interface An ordinary class or interface that is a direct member of a package. The basic Java class understood by the VM. All nested and inner classes are converted to this type.
Nested top-level class or interface A conveniently nested top-level class or interface. Must be declared static within another top-level class or interface. (Nested interfaces are implicitly static.) May use the static members of its containing type.

Inner classes

Member class A class defined as a member (non-static) of another. Each instance has an enclosing instance, and can use its members. New syntax for this, new, and super. Cannot have static members. Cannot have same name as a containing class.
Local class A class defined in a block of code. Can use members of enclosing classes and final local variables and parameters. New this syntax. Same restrictions as member classes.
Anonymous class Unnamed class defined within an expression. Has features of a local class. Allows a one-shot class to be defined exactly where needed. Same restrictions as local class, plus has no name or constructor. Only one instance of the class is created.