Nested and Inner Classes

Scroll down to class Car

Download this source file

// Nested class demo - shows one use of each type of nested or inner class.
// Although these classes don't do anything, it is useful to compile this
// file and observe the compiler generated names of the nested classes.
// Remember each class must end up in its own ".class" file, so what do
// you think the names of the annonymous classes will be?
//
// Written 4/2002 by Wayne Pollock, Tampa Florida USA.

class Base                     // normal class extended later
{
    void method1() {}
    void method2() {}
}

class Outer                     // normal class
{
    static class InnerStatic {} // nested class

    class Inner {}              // inner (non-static) class

    void f()
    {
       class Local_Inner {}      // local inner class
    }

    void g()
    {
        Base bref = new Base()  // anonymous class
        {  void method1()       // that extends "Base"
           {}                   // and overrides method1
        };
    }

    void h ( Base b ) {}

    void j ()
    {
        h( new Base()         // common use of annonymous inner class
          {                   // defined within a method call.
             void method2()
             {}
          }
        );
    }
}


InnerClassDemo.java

Download this source file

// Demo showing the special trust relationship of inner classes.
// It also shows the correct way to refer to enclosing class properties
// ("vehicleID") from inner class methods (this syntax is only needed
// if the name is shadowed), and how to construct inner class objects
// (which must be associated with an enclosing class object.)
//
// Written 4/2002 by Wayne Pollock, Tampa Florida USA.

class Car
{
   private String vehicleID;

   Car ( String vehicleID )
   {
      this.vehicleID = vehicleID;
   }

   class Motor
   {
      private String vehicleID = "123XYZ";

      void start ()
      {
         System.out.println( Car.this.vehicleID + " is running." );
      }
   }
}


public class InnerClassDemo
{
   public static void main ( String [] args )
   {
      Car ford = new Car( "Wayne's car" );
      Car.Motor motor = ford.new Motor();
      motor.start();
   }
}

Send comments and questions to pollock@acm.org.
Valid HTML 4.01!   Valid CSS!   CAST: Bobby WorldWide Approved 508   CAST: Bobby WorldWide Approved AAA