O'Reilly logo

Hardcore Java by Robert Simmons

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required