如何通过共享方法在 Java 中使用超类和子类

问题描述 投票:0回答:0

我有一个名为 Currency 的超类,我希望有一堆不同的子类继承这个超类,例如USD, GBP, YEN, 等等

这些子类中的每一个都具有相同的属性和方法。这些方法将返回相同类型的值,但方法主体需要略有不同。这是一个示例(我正在使用 API 调用来获取我拥有的每种货币的数量):

    public class USD extends Currency {
        
        public String symbol;
        public String holdings;
        public String bankAccountId; // Each currency has it's own account

        public float getHoldings(String apiKey) {
            HttpClient httpClient = HttpClient.newHttpClient();

            URI uri = new URIBuilder(apiBaseurl)
                .addParameter("module", "account")
                .addParameter("action", "tokenbalance")
                .addParameter("accountid", this.bankAccountId)
                .addParameter("apikey", apiKey)
                .build();
    
            HttpRequest getHoldingsRequest = HttpRequest.newBuilder()
                .uri(uri)
                .GET()
                .build();
    
            HttpResponse<String> response = httpClient.send(getHoldingsRequest, BodyHandlers.ofString());
    
            ObjectNode node = new ObjectMapper().readValue(response.body(), ObjectNode.class);
    
            return node.get("result").asFloat();
        }
    }

我的主要问题是我不想在每个子类中重复这个 getHoldings() 方法,所以我决定尝试把它放到 Currency 超类中,但是我有 2 个新问题:

  1. 我不能在方法中使用 this.bankAccountId(每种货币都保存在一个单独的帐户中,特定于该货币,我更愿意将 String bankAccountId 作为特定货币子类的属性)。
  2. 我无法遍历每种货币并对每种货币使用 getHoldings() 方法,如下所示:
    Portfolio portfolio = new Portfolio();
    String myApiKey = "duivbncvavsuivavcshinseo" // Some apiKey here
    
    portfolio.setOwnedCurrencies(Arrays.asList(
        new USD(),
        new GBP(),
        new YEN()    
    ));

    for (Currency currency : portfolio.getOwnedCurrencies()) {
        System.out.println(currency.getHoldings(myApiKey));
    }

我看过使用泛型,所以我可以拥有 Currency<USD>,但我不太清楚在这种情况下如何正确使用它们。我也觉得我在这里遗漏了一些非常基本/简单的东西,但我已经盯着这个问题看了这么久,我就是看不到它。

java generics subclass
© www.soinside.com 2019 - 2024. All rights reserved.