匿名內(nèi)部類 (new runnable)
1. 解釋:
2. 實(shí)例:
Demo1:
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(); } }
如果Child類使用一次,將變得多余,可以改為如下代碼
abstract class Person { public abstract void eat(); } ? public class Demo { public static void main(String[] args) { new Person(){ public void eat() { sout("eat !!!"); } }.eat(); } }
Demo2:
interface Person { public void eat(); } ? public class Demo { public static void main(String[] args) { new Person(){ public void eat() { sout("eat !!!"); } }.eat(); } }
此處 new Person( )看似實(shí)例化了一個(gè)接口,事實(shí)并非如此,接口式的匿名內(nèi)部類是實(shí)現(xiàn)了一個(gè)接口的匿名類。而且只能實(shí)現(xiàn)一個(gè)接口。
Demo3:
new Thread() { public void run() { for (int i = 1; i <= 5; i++) { System.out.print(i + " "); } } }.start();
Demo4:
new Thread(new Runnable() { @Override public void run() { int i=0; while(true){ i++; System.out.println("this is 線程"+i); } } }).start();
|