Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata