Java中匿名內部類

來源:互聯網
上載者:User

標籤:rac   dem   代碼   ring   something   並且   執行個體   interface   on()   

匿名內部類也就是沒有名字的內部類

正因為沒有名字,所以匿名內部類只能使用一次,它通常用來簡化代碼編寫

但使用匿名內部類還有個前提條件:必須繼承一個父類或實現一個介面

執行個體1:不使用匿名內部類來實現抽象方法
abstract class Person {    public abstract void eat();} class Child extends Person {    public void eat() {        System.out.println("eat something");    }} public class Demo {    public static void main(String[] args) {        Person p = new Child();        p.eat();    }}

運行結果:eat something

可以看到,我們用Child繼承了Person類,然後實現了Child的一個執行個體,將其向上轉型為Person類的引用

但是,如果此處的Child類只使用一次,那麼將其編寫為獨立的一個類豈不是很麻煩?

這個時候就引入了匿名內部類

執行個體2:匿名內部類的基本實現
abstract class Person {    public abstract void eat();} public class Demo {    public static void main(String[] args) {        Person p = new Person() {            public void eat() {                System.out.println("eat something");            }        };        p.eat();    }}

運行結果:eat something

可以看到,我們直接將抽象類別Person中的方法在大括弧中實現了

這樣便可以省略一個類的書寫

並且,匿名內部類還能用於介面上

執行個體3:在介面上使用匿名內部類
interface Person {    public void eat();} public class Demo {    public static void main(String[] args) {        Person p = new Person() {            public void eat() {                System.out.println("eat something");            }        };        p.eat();    }}

運行結果:eat something

由上面的例子可以看出,只要一個類是抽象的或是一個介面,那麼其子類中的方法都可以使用匿名內部類來實現

最常用的情況就是在多線程的實現上,因為要實現多線程必須繼承Thread類或是繼承Runnable介面

執行個體4:Thread類的匿名內部類實現
public class Demo {    public static void main(String[] args) {        Thread t = new Thread() {            public void run() {                for (int i = 1; i <= 5; i++) {                    System.out.print(i + " ");                }            }        };        t.start();    }}

運行結果:1 2 3 4 5

執行個體5:Runnable介面的匿名內部類實現
public class Demo {    public static void main(String[] args) {        Runnable r = new Runnable() {            public void run() {                for (int i = 1; i <= 5; i++) {                    System.out.print(i + " ");                }            }        };        Thread t = new Thread(r);        t.start();    }}

運行結果:1 2 3 4 5

Java中匿名內部類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.