我想用抽象函数calc()
声明一个抽象类,并将它与不同类型的参数一起使用。
public abstract class AbstractCalculation{
public abstract double calc();
...
}
public StringClass extends AbstractCalculation{
public double calc(String a, String b);
}
public DoubleClass extends AbstractCalculation{
public double calc(double a, double b);
}
我该如何解决这个问题?
答案 0 :(得分:5)
也许你的意思是像这样使用泛型:
public abstract class AbstractCalculation<T> {
public abstract double calc(T...params);//Here you can pass N param with any type
}
要从此抽象类扩展,您可以使用:
public class DoubleClass extends AbstractCalculation<Double> {
@Override
public double calc(Double... params) {
//Your action here
}
}
public class StringClass extends AbstractCalculation<String> {
@Override
public double calc(String... params) {
//Your action here
}
}
答案 1 :(得分:1)
使用泛型https://docs.oracle.com/javase/tutorial/java/generics/why.html
public abstract class Calculator<T, R>{
public abstract Double calc(T t, R r);
}
StringClass.java
public class StringClass extends Calculator<String, String>{
@Override
public Double calc(String t, String r) {
return null; //TODO your logic
}
}
<强> DoubleClass.java 强>
public class DoubleClass extends Calculator<Double, Double>{
@Override
public Double calc(Double t, Double r) {
return null; //TODO your logic
}
}
如果您需要灵活的退货类型。
<强> CalculatorV1.java 强>
public abstract class CalculatorV1<T, R, V> {
public abstract V calc(T t, R r);
}
<强> DoubleClassV1.java 强>
public class DoubleClassV1 extends CalculatorV1<Double, Double, Integer>{
@Override
public Integer calc(Double t, Double r) {
return null; //TODO your logic
}
}
答案 2 :(得分:1)