首頁  >  文章  >  Java  >  java中的匿名內部類別總結

java中的匿名內部類別總結

高洛峰
高洛峰原創
2016-12-15 12:19:291508瀏覽

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

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

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

 

實例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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn