簡體   English   中英

如何創建一個在java中實現公共接口的新對象數組

[英]how do I make an array of new objects that implement a common interface in java

這就是我試圖這樣做的方式:

interface a{} 
class b implements a{
    a[] array; 
    new b(){
        array={ new aImplementer(), new aImplementer(), new aImplementer()}; 
    } 
} 

為什么我不能這樣做? 我只是做錯了嗎? 現在,我得到的錯誤是{array = {的一部分表達錯誤的非法開始

您的語法已關閉。 我相信你想要這樣的東西(最終版本 - 這次實際測試 - 然后在我的更改被覆蓋后重做。)

interface A{} 

class AImplementer implements A{};

class B { 
    A[] array; 
    B(){  
        array=new A[]{ new AImplementer(), new AImplementer(), new AImplementer()}; 
    } 
 }

在那里,保證編譯或兩次你的錢:)

還免費提供“課程應以大寫字母開頭”。

在聲明變量時,您只能將數組分配給數組文字(我不確定您稱之為這些野獸)。 所以這可能沒問題

// array literal assigned at variable declaration
a[] array = { new aImplementer(), new aImplementer(), new aImplementer()};  
new b(){

} 

但是你首先聲明它然后在不同的位置分配它是不正確的。 為什么? 我不確定除了JLS之外的情況。

編輯:更新已編譯/測試的代碼:

interface A {
}

class AImplementer implements A {
};

class B {
   A[] array = {new AImplementer(), new AImplementer(), new AImplementer()};

   B() {

   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM