没错,这是一个方法,其中fun方法的参数是new创建的一个Action对象,但new后面的“{ }”及其中的内容如何理解?语法上怎么解释?这让人很困惑。

解决方案 »

  1.   

    try this you will know that 
    class A
    {
    public A()
      {
        print();
      }
    public void print()
    {
        System.out.println("aaa");
    }
    public void fun(B b){
    System.out.println("eee");
    }
    }
    class B extends A
    {
      public void print()
      {
        System.out.println("bbb");
      }
      
      
    }class Main{
                public Main(String a,String f,String c,String d,String e,B h){
       System.out.println(a+f+c+d+e);
       new B();
           }
    }public class test
    {
      public test()
      {
      }
      public static void main(String[] args)
      {
        B b=new B();
        A a=new A();
        a.fun(
            new B()
            {
                public void B(){
                   System.out.println("sha B");
                   print();
                
                }
                
                public void print(){
                 System.out.println("new B");
                }
                
                public Object run()
                {
                  new Main("i","c", "p", "l", "s",new B());
                  System.out.println("sss");
                  return null;
                }
                
            });
        a.print();
        a=b;
        a.print();
        b.print();
      }
    }
      

  2.   

    fun()的参数是一个Action类的实例。
    new Action(){...}是定义了一个匿名的Action类的子类。该子类提供了方法run();run()方法建立Main类的一个实例后返回。
      

  3.   

    就相当于fun方法需要的参数是一个Action类,这里只不过吧Action类要实现的东西在此直接实现了。
      

  4.   

    同意,匿名类。
    不过想到匿名类我有个问题问问:
       一个JFrame里有5JButton,每个按钮的事件都不一样,如果不用匿名类来addActionListener(),那应该怎么写?
      

  5.   

    to Patrick_DK(疾风摩郎):
    class MyActionListener implements ActionListener{
      public voud actionPerform(ActionEvent e){
        /*check source and deal with the things*/
       if(e.getSource() == ...)
       .....
      }
    }
    ......
    MyActionListener l = new MyActionListener();
    Button b[] = new Button[5];
    for(int i = 0;i<5;i++)
     b[i].addActionListener(l);
    ....