我正在编写一个简单的货币兑换应用程序。我有一个父类Currency
,它包含方法convertTo
和3个代表某些特定货币的子类。我想做的是使该convertTo
方法通用,以便我可以在子类上调用它并返回另一个子类的对象。
我最好的想法是使用泛型,但是在创建应返回泛型类型的方法时,遇到一个错误,提示我无法直接初始化原始类型。问题是如何在父类方法中初始化此类型? 请注意,我没有提供完整的代码,某些方法已跳过
public class Currency implements CurrencyUnit {
private CurrencyName name;
private BigDecimal amount;
private BigDecimal rate;
private BigDecimal spread;
public Currency() {}
public Currency(BigDecimal amount) {
if(BigDecimal.ZERO.compareTo(amount) > 0) {
throw new IllegalArgumentException("Amount can't be negative.");
}
this.amount = amount.setScale(SCALE, ROUNDING_MODE);
}
//method that should return subclass object
//currencyToConvert is Enum type
public Currency convertTo(CurrencyName currencyToConvert) throws IOException {
if (currencyToConvert.equals(this.getCurrencyName())) {
throw new IllegalArgumentException("Can't convert to same currency.");
}
String currencyUrl = "https://api.exchangeratesapi.io/latest%s%s";
String baseCurrencyUrl = String.format(currencyUrl, "?base=", this.getCurrencyName().toString());
RatesAPI ratesAPI = new RatesAPI(baseCurrencyUrl);
return new Currency(this.amount.multiply(ratesAPI.rateFromAPI(currencyToConvert.toString())));
}
}
//example of subclass (the other subclass for Dollar is basically the same only with currency name difference)
public class Euro extends Currency implements CurrencyUnit {
private final CurrencyName eur = CurrencyName.EUR;
public Euro() {}
public Euro(BigDecimal amount) {
super(amount);
}
public Euro(BigDecimal amount, BigDecimal rate, BigDecimal spread) {
super(amount, rate, spread);
}
@Override
public CurrencyName getCurrencyName() {
return eur;
}
//and the example of Main method
public class Main {
public static void main(String[] args) throws IOException {
Currency eur = new Euro(BigDecimal.ONE);
Currency usd = new Dollar(BigDecimal.ONE);
System.out.println(eur);
usd = eur.convertTo(CurrencyName.USD);
System.out.println(usd);
我要实现的是在convertTo
类对象上调用Euro
方法,以便该方法返回例如美元类对象。如前所述,对我而言,最优雅的解决方案似乎是使用泛型类型。当我创建类Currency<T>
并在Dollar
上调用方法并作为方法参数时,我使用Currency<T>
对象遇到了创建的“无法转换为相同货币”的异常,这看起来很合逻辑。
我不是在寻找问题的直接答案,只是在寻找一些指导,因为这些泛型对我来说相当复杂。
我尝试在Web上搜索答案,实际上,我发现了this,但它显示了如何返回调用了该方法的对象。