2010-10-16 47 views
9
interface Int { 
    public void show(); 
} 

public class Test {  
    public static void main(String[] args) { 
     Int t1 = new Int() { 
      public void show() { 
       System.out.println("message"); 
      } 
     }; 

     t1.show(); 
    } 
} 

回答

16

您正在定義一個實現接口Int的匿名類,並立即創建一個類型爲thatAnonymousClassYouJustMade的對象。

+2

這對於事件處理程序(如使用ActionListener接口的那些處理程序)非常有用。 – 2010-10-16 04:49:04

4

匿名內部類的這種特殊語法在底層做了什麼:創建一個名爲Test$1的類。您可以在Test類旁邊的類文件夾中找到該類文件,並且如果您打印了t1.getClass().getName(),則可以看到該文件。

7

這種表示法的簡寫

Int t1 = new MyIntClass(); 

// Plus this class declaration added to class Test 
private static class MyIntClass implements Int 
    public void show() { 
     System.out.println("message"); 
    } 
} 

那麼,到底你要創建一個具體的類,其行爲已定義內嵌的一個實例。

你也可以用抽象類來做到這一點,通過提供所有內聯抽象方法的實現。

0

我覺得你的對象與界面無關。如果你註釋掉整個界面,你仍然會得到相同的輸出。它只是創建了一個匿名類。我認爲,除非你使用類「實現」你不能實現接口。但我不知道如何命名碰撞不會發生在你的情況。

+0

匿名類明確實現了接口,並且't1 instanceof Int'將成立。 – Thilo 2010-10-17 01:37:54

相關問題