內部類學習(四)--匿名內部類

來源:互聯網
上載者:User

這裡再介紹一種特殊的內部類――匿名內部類(Anonymous Inner Class),顧名思義,就是沒有名字的內部類,這是Java為了方便我們編寫程式而設計的一個機制。因為有時候有的內部類只需要建立一個它的對象就可以了,以後再不會用到這個類,這時候使用匿名內部類就比較合適,而且也免去了給它取名字的煩惱,:)。

匿名類的文法是什麼樣的呢?如下所示:

new SuperType(){

    內部類的方法和域;

}

注意,這裡的SuperType指超類,它可以是一個介面(interface)或者是一個類(Class),當它是一個介面的時候就不能有構造參數(Construction parameters)了。匿名類的文法相對於Java的其他部分來說稍微複雜一點,我們可以按如下方式理解:

1.SuperType為介面

例子:Interface1() test=new Interface1(){

          要實現的的方法;

          Interface1的域;

          內部類的域以及方法;

}

我們可以如下理解:

先聲明了如下一個類,

      class Anonymous1 implements Interface1{

          要實現的的方法;

          Interface1的域;

          內部類的域以及方法;

}

然後,Interface1() test=new Anonymouse1();

這樣就比較容易理解了。

2.SuperType為類

例子:Class2 test=new Class2(Construction parameters){

          內部類的域以及方法;

}

我們可以如下理解:

先聲明了如下一個類,

      class Anonymous2 extends Class2{

          public Anonymous2(Construction parameters){

    super(Construction parameters);

}

內部類的域以及方法;

}

然後,Class2 test=new Anonymouse2(Construction parameters);

本節測試代碼如下:

 

 

 

 

package cn.edu.hust.cm.test;

 

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

import java.awt.Toolkit;

 

import javax.swing.JOptionPane;

import javax.swing.Timer;

public class InnerClassTest {

       public InnerClassTest() {

              super();

       }

       public static void main(String[] args) {

        Court court=new Court(10000,true);

        court.start();

        JOptionPane.showMessageDialog(null,"停止麼,CMTobby?");

        System.exit(0);

     }

 

}

 

class Court{

      

       public Court(int interval,boolean beep){

              this.interval=interval;

              this.beep=beep;

       }

      

       public void start(){

              ActionListener action=new ActionListener(){

                     public void actionPerformed(ActionEvent e){

                            System.out.println("Cindyelf,wouly you be my girl?");

                     }

              };

              Timer t=new Timer(interval,action);

              t.start();

             

       }

       private int interval;

       private boolean beep;

}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.