java 匿名内部类

java 匿名内部类


1.就是没有类名字的类,在另一个类中实现的
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();
    }
}



在接口上使用匿名内部类
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();
    }
}



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接口的匿名内部类实现
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://www.cnblogs.com/nerxious/archive/2013/01/25/2876489.html

猜你喜欢

转载自huangyongxing310.iteye.com/blog/2329601