Chapter 6. Nested Classes

One aspect of the Java language that is not widely understood is the concept of nested classes. These classes allow you to constrain an entire class within a limited scope of another class or method. The concept of nesting a class within another class or method presents unique issues not found elsewhere in object-oriented programming. Not all types of nested classes should be used routinely, so you will likely encounter most of them in other people’s code. Therefore, it is important that you understand how the various nested classes function.

Nested classes fall into one of three basic categories:

  • Inner classes

  • Limited-scope inner classes

  • Static nested classes

Each of these categories has its own access rules and usage.

Inner Classes

Inner classes are fairly common within the JDK, especially in collections. Example 6-1 shows a class-scoped inner class.

Example 6-1. A class-scoped inner class
package oreilly.hcj.nested;
public class InnerClassDemo extends JDialog {

  public InnerClassDemo(final int beepCount) {
    super( );
    setTitle("Anonymous Demo");
    contentPane = getContentPane( );
    contentPane.setLayout(new BorderLayout( ));

    JLabel logoLabel = new JLabel(LOGO);
    contentPane.add(BorderLayout.NORTH, logoLabel);

    JButton btn = new BeepButton("Beep");
    contentPane.add(BorderLayout.SOUTH, btn);
    pack( );
    this.beepCount = beepCount;
  }

  private class BeepButton extends JButton implements ActionListener {

                   public BeepButton(final String text) {
                     super(text);
                addActionListener(this); ...

Get Hardcore Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.