Core Java学习笔记 内部类

Posted on 2010-05-16 21:26 eric_xu 阅读(326) 评论(0)  编辑  收藏 所属分类: Java
 

内部类是定义在一个类内部的类。

内部类方法可以访问该类定义所在的作用域的数据,包括私有数据。

内部类对同一包中的其他类不可见。

使用内部类定义回调函数可以避免写大量代码。

class TalkingClock

{

   public TalkingClock(int interval, boolean beep) { . . . }

   public void start() { . . . }

   private int interval;

   private boolean beep;

   private class TimePrinter implements ActionListener

      // an inner class

   {

     Date now = new Date();
      System.out.println("At the tone, the time is " + now);
      if (beep) Toolkit.getDefaultToolkit().beep();

   }

}

内部类既可以访问自身的数据域,也可以访问创建它的外围类对象的数据域。内部类有一个隐式引用,其指向外围类对象。


public void actionPerformed(ActionEvent event)

   Date now = new Date();

   System.out.println("At the tone, the time is " + now);

   if (outer.beep) Toolkit.getDefaultToolkit().beep();

}

内部类的默认构造函数

public TimePrinter(TalkingClock clock) // automatically generated code
{
     outer = clock;
}

局部内部类,不能用privatepublic声明,start方法都不能访问它。

public void start()
{
   class TimePrinter implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
          Date now = new Date();
          System.out.println("At the tone, the time is " + now);
          if (beep) Toolkit.getDefaultToolkit().beep();
      }
   }
   ActionListener listener = new TimePrinter();
   Timer t = new Timer(1000, listener);
   t.start();
}

匿名内部类

public void start(int interval, final boolean beep)
{
   ActionListener listener = new
      ActionListener()
      {
         public void actionPerformed(ActionEvent event)
         {
             Date now = new Date();
             System.out.println("At the tone, the time is " + now);
             if (beep) Toolkit.getDefaultToolkit().beep();
         }
      };
   Timer t = new Timer(1000, listener);
   t.start();
}

匿名构造了不能有构造函数,而是把构造函数参数传递给超类构造函数,

new SuperType(construction parameters)
{
   inner class methods and data
}

内部类实现接口时,不能有任何参数

new InterfaceType() { methods and data }

静态内部类

class ArrayAlg
{
   public static class Pair
   {
      . . .
   }
   . . .
}

静态内部类对象除了没有对生产它的外部类对象的引用特权外,与其他的内部类完全一样。


只有注册用户登录后才能发表评论。


网站导航:
 

posts - 37, comments - 5, trackbacks - 0, articles - 0

Copyright © eric_xu