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

猜你喜欢

转载自blog.csdn.net/qq_23864697/article/details/83587423