匿名內部類也就是沒有名字的內部類,正因爲沒有名字,所以匿名內部類只能使用一次,它通常用來簡化代碼編寫。
但使用匿名內部類還有個前提條件:必須繼承一個父類或實現一個接口
1、繼承一個父類的匿名內部類實現:
- abstract class People {
- public abstract void eat();
- }
- public class Demo {
- public static void main(String[] args) {
- People p = new People() {
- public void eat() {
- System.out.println("I can eat ");
- }
- };
- p.eat();
- }
- }
2、在接口上使用匿名內部類:
- interface People {
- public void eat();
- }
- public class Demo {
- public static void main(String[] args) {
- People p = new People() {
- public void eat() {
- System.out.println("I can eat ");
- }
- };
- p.eat();
- }
- }
此處 new People( )看似實例化了一個接口,事實並非如此,接口式的匿名內部類是實現了一個接口的匿名類。而且只能實現一個接口。
ps再來說一下線程創建的兩種方式:
(1)繼承Thread類的方式因爲耦合性太強,所以一般不用。
(2)常用實現Runnable接口的創建線程方式。
但是我們更喜歡用匿名內部類的方式來創建一個線程。代碼如下:
- new Thread(new Runnable() {
- @Override
- public void run() {
- int i=0;
- while(true){
- i++;
- System.out.println("this is 線程"+i);
- }
- }
- }).start();
就這一句話就可以創建並且啓動一個線程,相對來說比較方便。而且特別直觀易懂。
此處的new Runnable( )並沒有實例化了一個接口,切記切記!!!!