Rice University - Comp 212 - Intermediate Programming

Fall 2001

Lecture #14 - Nested Classes vs. Inner Classes  and Closure


Besides fields and methods, a Java class can also contain other classes.

class X {
    // fields of X ...
    // methods of X ...
    
    /** 
    * class defined inside of X:
    */

    [public | protected | private]  [static]  [final]  [abstract]  class Y [ extends A]  [implements B]  {
        // fields of Y ...
        // methods of Y ...
        // classes of Y ...
    }
}

Access specifier:

Just like any other class, a class defined inside of another class can be public, protected, package private, or private.

Scope specifier:

Just like any other class, a class defined inside of another class can be static or non-static. 

When it is defined as static, it is called a nested class. The members (i.e. fields, methods, classes) of a (static) nested class can access to only static members of the enclosing class.

When it is non-static, it is called an inner class. The members of an inner class can access ALL members of the enclosing class. The enclosing class (and its enclosing class, if any, and so on) contains the environment that completely defines the inner class and constitutes what is called the closure of the inner class.  As all functional programmers should know, closure is a powerful concept.  One of the greatest strength in the Java programming language is the capability to express closures via classes with inner classes.  We shall see many examples that will illustrate this powerful concept during the rest of the semester.

Extensibility Specifier:

Just like a regular class, a final  nested/inner class cannot extended.  

Abstract Specifier:

Just like a regular class, an abstract nested/inner class cannot be instantiated.

Inheritance Specifier:

Just like a regular class, an nested/inner can extend any non-final class and implement any number of interfaces that are within its scope.

Usage: 

Nested classes are used mostly to avoid name clash and to promote and enforce information hiding.  Examples?

Inner classes are used to create objects that have direct access to the internals of the outer object and perform complex tasks that simple methods
cannot do.  Take a look at this example and experiment with it with DrJava.

An inner object can be thought as an extension of the outer object.

Event listeners for a Java GUI components are implemented as inner classes.

In the state design pattern, the states of an object are often implemented as inner objects. Since an inner object has access to its outer object (the context), there is no need to have setter and getter methods for the state.

See the Java Resources web page on inner classes.