public interface Function {

    double apply(double arg);

    Function derivative();

    String toString();

}

public interface Integrable extends Function {

    Function integrate();

}

public class Sum implements Function {

    private Function func1, func2;

    public Sum(Function func1, Function func2) {
        this.func1 = func1;
        this.func2 = func2;
    }

    @Override
    public double apply(double arg) {
        return func1.apply(arg) + func2.apply(arg);
    }

    @Override
    public Function derivative() {
        return new Sum(func1.derivative(), func2.derivative());
    }

    @Override
    public String toString() {
        return func1.toString() + " + " + func2.toString();
    }

    @Override
    public Function integrate() {
        //TODO only allow if (this instanceof Integrable)
        try {
            return new Sum(((Integrable) func1).integrate(), ((Integrable) func2).integrate());
        } catch (ClassCastException e) {
            throw new RuntimeException("could not call integrate on one of the functions of this sum, as it is not of type Integrable");
        }
    }

}


我正在尝试制作上面的Sum类,但是如果两个函数也是Integrable,则它只能是Integrable类型。否则,它应该只是一个Function

有什么方法可以有效地做到这一点,还是最好将其默认设置为Integrable并检查integrate()中的2个字段?

最佳答案

我要说的是,在这种情况下,Sum的参数必须采用Integrable

您可以创建两个类-SumIntegrableSum(嗯。需要更好的名称)

class Sum implements Function {
    public Sum(Function func1, Function func2) {
       ....
    }
}

class IntegrableSum implements Integrable {
    public IntegrableSum(Integrable integrable1, Integrable integrable2) {
       ....
    }
}

10-08 20:21