黑马程序员技术交流社区

标题: 匿名内部类 [打印本页]

作者: zhonggege1234    时间: 2015-9-25 21:47
标题: 匿名内部类
匿名内部类有什么用,可不可以举个例子
作者: maxwell247    时间: 2015-9-25 22:21
匿名内部类启动线程, 安卓里面监听器 handler 等等,都有匿名内部类。
作者: ringfingers    时间: 2015-9-25 22:42
在接口上使用匿名内部类
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();
    }
}
作者: ringfingers    时间: 2015-9-25 22:44
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();
    }
}


Runnable接口的匿名内部类实现
1
2
3
4
5
6
7
8
9
10
11
12
13
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();
    }
}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2