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(); } }
運行結果:eat somethingjava
能夠看到,咱們用Child繼承了Person類,而後實現了Child的一個實例,將其向上轉型爲Person類的引用多線程
可是,若是此處的Child類只使用一次,那麼將其編寫爲獨立的一個類豈不是很麻煩?spa
這個時候就引入了匿名內部類線程
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(); } }
運行結果:eat somethingcode
能夠看到,咱們直接將抽象類Person中的方法在大括號中實現了繼承
這樣即可以省略一個類的書寫接口
而且,匿名內部類還能用於接口上class
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(); } }
運行結果:eat something引用
由上面的例子能夠看出,只要一個類是抽象的或是一個接口,那麼其子類中的方法均可以使用匿名內部類來實現方法
最經常使用的狀況就是在多線程的實現上,由於要實現多線程必須繼承Thread類或是繼承Runnable接口
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(); } }
運行結果:1 2 3 4 5
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(); } }