java anonymous inner class

Java anonymous inner class


1. It is a class without a class name, implemented in another class
2. It is the basic implementation of


anonymous
abstract class Person {
    public abstract void eat();
}

public class Demo {
    public static void main(String[] args) {
        Person p = new Person() {//Create an anonymous inner class here
            public void eat() {
                System.out.println("eat something");
            }
        };
        p.eat();
    }
}



Using anonymous inner classes on interfaces
interface Person {
    public void eat();
}

public class Demo {
    public static void main(String[] args) {
        Person p = new Person() {//Create an anonymous inner class here
            public void eat() {
                System.out.println("eat something");
            }
        };
        p.eat();
    }
}



Anonymous inner class implementation of Thread class
public class Demo {
    public static void main(String[] args) {
        Thread t = new Thread() {//Create an anonymous inner class here
            public void run() {
                for (int i = 1; i <= 5; i++) {
                    System.out.print(i + " ");
                }
            }
        };
        t.start();
    }
}



Anonymous inner class implementation of Runnable interface
public class Demo {
    public static void main(String[] args) {
        Runnable r = new Runnable() {//Create an anonymous inner class here
            public void run() {
                for (int i = 1; i <= 5; i++) {
                    System.out.print(i + " ");
                }
            }
        };
        Thread t = new Thread(r);
        t.start();
    }
}



Reference original text: http://www.cnblogs.com/nerxious/archive/2013/01/25/2876489.html

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326982485&siteId=291194637