簡體   English   中英

將超類 object 作為參數傳遞給具有子類參數的方法

[英]Passing a superclass object as a parameter to a method with a subclass parameter

在下面的代碼中,“NPC”和“Settlement”都是超類“Feature”的子類(我刪除了 generateNewRelationships() 方法的不相關部分)

public ArrayList<Relationship> generateNewRelationships(ArrayList<Feature> features) {
    for(Feature feature: features) {
        ArrayList<Predicate> possiblePredicates = filterPredicates(feature, subjectPredicates);
    }
}

private ArrayList<Predicate> filterPredicates(NPC npc, ArrayList<Predicate> npcPredicates) {
    // Does NPC filter
}

private ArrayList<Predicate> filterPredicates(Settlement settlement, ArrayList<Predicate> settlementPredicates) {
    // Does Settlement filter
}

現在 filterPredicates 方法的調用不起作用,因為沒有將“Feature”作為參數類型的方法。 有沒有辦法轉換“特征”變量,以便將其轉換為它實際引用的子類型,以便使用正確的方法?

我想避免手動寫出 if/else 或 switch 語句,因為將來會有更多的 Feature 子類。

永遠不會有“特征”的實例,只有其子類的實例,因此 ArrayList 特征將永遠只包含 NPC 或定居點。

(這是我的問題的轉貼,因為它已關閉說 PECS(生產者擴展消費者超級)是解決方案,但這是關於將 collections 作為參數傳遞。我的問題是關於如何編寫對“filterPredicates(feature,subjectPredicates)的調用)' 其中單個 object 'feature' 將在 for 循環內的 Feature 子類型 'NPC' 和 'Settlement' 之間交替,因此 'feature' 被轉換為 NPC 或 Settlement,具體取決於子類型 'feature' 實際持有的位置那時。)

正如丁丁所說,如果沒有更多示例代碼和細節,很難給出一個真正好的答案。

但是您有一個可以回答的具體問題: “有沒有一種方法可以轉換‘特征’變量,以便將其轉換為它實際引用的子類型,從而使用正確的方法?”

如果要將Feature轉換為子類型,則需要首先確定要轉換為的子類型。 如果有許多可能的子類型,您需要檢查它使用的是哪一個instanceof 但你提到你不想這樣做。

因此,為了避免instanceof檢查,您需要使用Feature而不是子類。

這里一種可能的選擇是簡單地更新Feature界面,以便它可以用於您想要做的事情。 您可以將 function 添加到名為matchesPredicateFeature中,並為NPCSettlement以不同的方式實現它。 然后filterPredicates可以變成這樣:

// matchesPredicate looks like this: "public boolean matchesPredicate(Predicate p){...}"

private ArrayList<Predicate> filterPredicates(Feature feature, ArrayList<Predicate> predicates) {
    
   ArrayList<Predicate> result = new ArrayList();
   for (Predicate p : predicates) {
       if (feature.matchesPredicate(p)) {
           result.add(p);
       }
   }

   return result;
}

(注意:在回答這個問題時,您沒有寫filterPredicates function 正文所做的事情,所以我在這里用該代碼猜測了一下。)

暫無
暫無

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

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