2013-09-26 87 views
0

試圖實例化類時出現 - an enclosing instance that contains的原因是什麼?無法創建類的實例

下面是我的實際代碼:

public static void main(String[] args) { 
    InterspecTradeItems_Type.Item_Type item = new InterspecTradeItems_Type.Item_Type(); 
    // Error: an enclosing instance that contains InterspecTradeItems_Type.Item_Type is required 

} 


public class InterspecTradeItems_Type { 
    public class Item_Type { 

    } 
} 

感謝。

+0

(HTTP [包含<我的參考>需要一個外圍實例]的可能重複:// stackoverflow.com/questions/4297857/an-enclosing-instance-that-c​​ontains-my-reference-is-required) –

+0

如果您不需要Item_Type中的封閉類的實例,則應該將其設置爲靜態。 – NeplatnyUdaj

回答

2

As Item_Type is inner class。要實例化一個內部類,你必須首先實例化外部類。然後,使用此語法外部對象內創建內部對象:

InterspecTradeItems_Type.Item_Type項=新InterspecTradeItems_Type()新ITEM_TYPE();

1

假設InterspecTradeItems_Type聲明/在一個名爲Main類中定義的,你需要

InterspecTradeItems_Type.Item_Type item = new Main(). 
           new InterspecTradeItems_Type().new Item_Type(); 

您已在一個內部類和內部類。你需要每個外部類的實例來獲取它。

2

由於Item_Type類不是一個靜態嵌套類,而是一個InterspecTradeItems_Type的內部類,您需要一個後面的實例來訪問前者。

所以,要創建內部類的一個實例,你應該創建外圍類的實例:

new InterspecTradeItems_Type().new Item_Type(); 

當然,另一種選擇是讓Item_Type一個static類:

public class InterspecTradeItems_Type { 
    public static class Item_Type { 

    } 
} 

然後你的代碼將工作得很好。

+2

...或使Item_Type爲靜態。還要注意'Item_Type' *是一個嵌套類。所有內部類都是按定義嵌套的。 JLS第8.1.3節:「內部類是一個嵌套類,不明確或隱式地聲明爲靜態。「 –

+0

請注意,因爲'InterspecTradeItems_Type'不是'static',所以你需要一個外部類的實例來實例化它。 –

+0

@SotiriosDelimanolis。你從哪裏推斷'InterspecTradeItems_Type'是一些外部類的內部類? –

0

要實例化一個內部類,必須首先實例化外部類。然後,創建外部對象內的內部對象與此語法:

OuterClass.InnerClass innerObject = outerObject.new InnerClass(); 

所以上面的語法或者使用或者使Item_Type靜態

public static void main(String[] args) { 
    InterspecTradeItems_Type.Item_Type item = new InterspecTradeItems_Type. 
                    Item_Type(); 
    // Error: an enclosing instance that contains 
           InterspecTradeItems_Type.Item_Type is required 

}  
public class InterspecTradeItems_Type { 
    public static class Item_Type { 

    } 
} 

閱讀docs在內部類的更多信息。

0

嘗試

public static void main(String[] args) { 
    InterspecTradeItems_Type item = new InterspecTradeItems_Type(); 
    Item_Type item1 = item.new Item_Type(); 

} 
0

的正確方法具有內部類的一個目的是

InterspecTradeItems_Type.Item_Type item = new InterspecTradeItems_Type.new Item_Type();