Recipe 9.6 Using Inner Classes


Problem

You need to write a private class, or a class to be used in one other class at the most.

Solution

Use a nonpublic class or an inner class.

Discussion

A nonpublic class can be written as part of another class's source file, but it is not included inside that class. An inner class is Java terminology for a nonstatic class defined inside another class. Inner classes were first popularized with the advent of JDK 1.1 for use as event handlers for GUI applications (see Recipe 14.4), but they have a much wider application.

Inner classes can, in fact, be constructed in several contexts. An inner class defined as a member of a class can be instantiated anywhere in that class. An inner class defined inside a method can be referred to later only in the same method. Inner classes can also be named or anonymous. A named inner class has a full name that is compiler-dependent; the standard JVM uses a name like MainClass$InnerClass.class for the resulting file. An anonymous inner class, similarly, has a compiler-dependent name; the JVM uses MainClass$1.class, MainClass$2.class, and so on.

These classes cannot be instantiated in any other context; any explicit attempt to refer to, say, OtherMainClass$InnerClass, is caught at compile time:

import java.awt.event.*; import javax.swing.*; public class AllClasses {     /** Inner class can be used anywhere in this file */     public class Data {         int x;         int y;     }     public void getResults( ) {         JButton b = new JButton("Press me");         b.addActionListener(new ActionListener( ) {             public void actionPerformed(ActionEvent evt) {                 System.out.println("Thanks for pressing me");             }         });     } } /** Class contained in same file as AllClasses, but can be used  * (with a warning) in other contexts.  */ class AnotherClass {     // methods and fields here... }



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net