Java中的匿名內部類總結

EmileMoriar 8年前發布 | 6K 次閱讀 Java Java開發

匿名內部類也就是沒有名字的內部類

正因為沒有名字,所以匿名內部類只能使用一次,它通常用來簡化代碼編寫

但使用匿名內部類還有個前提條件:必須繼承一個父類或實現一個接口

實例1:不使用匿名內部類來實現抽象方法

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 something

可以看到,我們用Child繼承了Person類,然后實現了Child的一個實例,將其向上轉型為Person類的引用

但是,如果此處的Child類只使用一次,那么將其編寫為獨立的一個類豈不是很麻煩?

這個時候就引入了匿名內部類

實例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();   
     }   
 }

運行結果: eat something

可以看到,我們直接將抽象類Person中的方法在大括號中實現了

這樣便可以省略一個類的書寫

并且,匿名內部類還能用于接口上

實例3:在接口上使用匿名內部類

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接口

實例4: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();         
       }         
   }

運行結果: 1 2 3 4 5

實例5: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();   
     }   
 }

運行結果:1 2 3 4 5

 

來自:http://mp.weixin.qq.com/s/EVfis8nf1fsth1LTCwPzyQ

 

 本文由用戶 EmileMoriar 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!