core java中的程序,讨论内部类。import java.awt.event.*;
import java.text.*;
import javax.swing.*;public class InnerClassTest
{  
   public static void main(String[] args)
   {  
      // construct a bank account with initial balance of $10,000
      BankAccount account = new BankAccount(10000);
      // start accumulating interest at 10%
      account.start(10);      // keep program running until user selects "Ok"
      JOptionPane.showMessageDialog(null, "Quit program?");
      System.exit(0);
   }
}class BankAccount
{  
   /**
      Constructs a bank account with an initial balance
      @param initialBalance the initial balance
   */
   public BankAccount(double initialBalance)
   {  
      balance = initialBalance;
   }   /**
      Starts a simulation in which interest is added once per
      second
      @param rate the interest rate in percent
   */
   public void start(double rate)
   {
      ActionListener adder = new InterestAdder(rate);
      Timer t = new Timer(1000, adder);
      t.start();
   }   private double balance;   /**
      This class adds the interest to the bank account. 
      The actionPerformed method is called by the timer.
   */
   private class InterestAdder implements ActionListener
   {  
      public InterestAdder(double aRate)
      {
         rate = aRate;
      }      public void actionPerformed(ActionEvent event)
      {  
         // update interest
         double interest = balance * rate / 100;
         balance += interest;         // print out current balance
         NumberFormat formatter 
            = NumberFormat.getCurrencyInstance();
         System.out.println("balance=" 
            + formatter.format(balance));
      }      private double rate;
   }
}我的问题是:
1,ActionListener adder = new InterestAdder(rate);这条语句中ActionListener是一个接口,InterestAdder是一个实现了这个接口的类,这种定义形式有什么作用,体现了java的什么特性,照我的理解定义为InterestAdder adder = new InterestAdder(rate);也可以呀。
2,InterestAdder是BankAccount的内部类,产生了InterestAdder对象后会不会产生一个BankAccount对象,为什么?怎么去验证您的看法。

解决方案 »

  1.   

    1.你把ActionListener想成父类就能理解了,这是非常常用的方式,很多设计模式都要靠这个特性来实现,体现了多态和继承。
    如果还有一个实现了ActionListener接口的类B,要是你不知道到底是InterestAdder类还是B类时,都用ActionListener就可以统一表示了。
    2.内部类可以调用上层类的成员,但要求必须是FINAL类型。
      

  2.   

    内部类有许多好处,比如可以访问它外面类的private属性的方法和变量。
    可以使代码写的更简洁。可以使用匿名类,这样就可以保证安全性
      

  3.   

    2 当你编译这个文件时,会有一个 InnerClassTest$InterestAdder.class 产生
    不会的,运行后只打出了 test
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class test extends JFrame{
    class inner{
    inner(){
    System.out.println("inner");
    }
    }
    test(){
    System.out.println("test");
    }
    public static void main(String[] args){
    test a=new test();

    }
      

  4.   

    消化中。
    thanks  airhand(暴风雨) 
    thanks  wuyafeixue(蓝色天空)