2013-07-22 37 views
1

當我創建一個Abstract類的對象時,我必須像界面一樣這樣做。抽象類的對象是匿名內部類嗎?

AbstractClass abstractClass = new AbstractClass() { 

      @Override 
      public void abstractMethod() { 
      } 
     }; 

這是否意味着AbstractClass的對象是一個匿名的內部類對象?

+0

這種不公平的傢伙,爲什麼-ve?無論如何,我得到了我的答案。我會盡快刪除它。 – Mawia

回答

1

對象不是類對象(在此上下文中)。它來自一個類。在Java中,類與對象之間有區別,基於原型的語言(例如JavaScript),其中不存在這種差異。

在您的示例中,您將創建一個匿名類,創建該匿名類的一個對象並將其分配給一個變量;一步到位。

匿名的課總是內部類:http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9.5 http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.3

2
AbstractClass abstractClass = new AbstractClass() { 

      @Override 
      public void abstractMethod() { 
      } 
     }; 

這塊代碼意味着你正在創建一個匿名類,它擴展了AbstractClass。您也可以對接口使用相同的符號。

SomeInterface someImplementingClass = new SomeInterface(){/*some code here*/}; 

這意味着您正在創建一個實現SomeInterface的類。

請注意,創建匿名類時存在一定的侷限性。由於匿名類已經擴展了父類型,所以不能像擴展java一樣只擴展類。

這個代碼將有助於瞭解的首要方法概念匿名類

class Anonymous { 
    public void someMethod(){ 
     System.out.println("This is from Anonymous"); 
    } 
} 

class TestAnonymous{ 
    // this is the reference of superclass 
    Anonymous a = new Anonymous(){ // anonymous class definition starts here 
     public void someMethod(){ 
      System.out.println("This is in the subclass of Anonymous"); 
     } 
     public void anotherMethod(){ 
      System.out.println("This is in the another method from subclass that is not in suprerclass"); 
     } 
    }; // and class ends here 
    public static void main(String [] args){ 
     TestAnonymous ta = new TestAnonymous(); 
     ta.a.someMethod(); 
    // ta.a.anotherMethod(); commented because this does not compile 
    // for the obvious reason that we are using the superclass reference and it 
    // cannot access the method in the subclass that is not in superclass 
    } 

} 

此輸出

This is in the subclass of Anonymous 

記住anotherMethod是在被匿名類創建的子類實現來實現。而aAnonymous類型的參考變量,即匿名類的超類。所以聲明ta.a.anotherMethod();給出編譯器錯誤,因爲anotherMethod()Anonymous中不可用。

0

一個吸引階級的根本屬性是事實,有可能是這種類型的沒有直接的實例。只有實現一個類的完整接口的類才能被實例化。 爲了創建一個對象,首先需要一個非抽象類,通過擴展抽象類。

0

其實這裏創建兩個:一個匿名內部類,即擴展AbstractClass以及本anonyomous類的一個實例,在對象。您不能也不能創建AbstractClass的實例。

另外您還聲明瞭一個名爲abstractClass的變量,其類型爲AbstractClass。這裏面變量存儲您新定義子類的AbstractClass的新創建實例。

編輯:你當然可以不重複使用匿名內部類,因爲它是匿名的,並在它的一個實例可以創造的唯一的地方或者說創建是正確這裏

這裏可能是一個循環或函數,在這種情況下,你將能夠創建這個匿名內部類的許多實例。但它仍然只是創建實例的這段代碼。

0

不能創建一個抽象類的一個對象。它們是不可實例化的。什麼,當你這樣做,你正在做的是建立一種動態的子類的對象,並實例(在同一時間)。或多或少,是的,你可以像界面一樣創建它。有關更多信息,請參閱this answer