1. 程式人生 > >java中匿名內部類的理解

java中匿名內部類的理解

如下面:

    Runnable runnable = new Runnable() {
                @Override
                public void run() {

                }
            };
1
2
3
4
5
6
    new View.OnClickListener(){
            @Override
            public void onClick(View v) {

            }
        };
1
2
3
4
5
6
上面是我們平時經常用的方法,它們就是典型的匿名內部類,但是我沒從這裡看出來它們什麼類沒有名字,不過知道new 一個介面肯定是不合理的,下面就將匿名還原:

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();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
可以看到,我們用Child繼承了Person類,然後實現了Child的例項,將其向上轉型為Person抽象類的引用,而Child類就是我們在匿名內部類中隱藏的類,寫成匿名類:

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();
    }
}