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 non-public class or an inner class.

Discussion

A non-public class can be written as part of another class’s source file, but is not included inside that class. An inner class is Java terminology for a 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 Section 13.5), 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 only be referred to later 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, will be 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...
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.176.72