简体   繁体   English

如果字段实现该接口,则如何实现该接口

[英]How to implement an interface if a field implements that interface

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");
        }
    }

}

I'm trying to make the Sum class above, but it should only be of type Integrable if both functions are also Integrable . 我正在尝试使Sum类成为上面的类,但是如果两个函数也是Integrable ,则它只能是Integrable类型。 Otherwise, it should just be a Function . 否则,它应该只是一个Function

Is there any way to do this efficiently, or is it better to make it Integrable by default and check the 2 fields in integrate() ? 有什么方法可以有效地做到这一点,还是最好使它默认为Integrable integrate()并检查integrate()的2个字段?

I would say that that the parameter of Sum must take an Integrable in that case. 我要说的是, Sum的参数在这种情况下必须是Integrable

You can create two classes - Sum and IntegrableSum (uhh.. need a better name) 您可以创建两个类SumIntegrableSum (嗯。需要更好的名称)

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

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

I'd suggest you create adapter classes that implement the Integrable interface, provide default implementations to the respective abstract methods of your choice. 我建议您创建实现Integrable接口的适配器类,并为您选择的各个抽象方法提供默认实现。 But I don't think you can create a class in Java based on conditions as classes created in Java is direct, I mean you should know what your class is all about before creation. 但是我认为您不能根据条件在Java中创建类,因为用Java创建的类是直接的,我的意思是您应该在创建之前就知道您的类的全部内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM