Jaïr Paalman
Jaïr Paalman

Reputation: 278

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. Otherwise, it should just be a 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()?

Upvotes: 0

Views: 61

Answers (2)

Dexter
Dexter

Reputation: 114

I'd suggest you create adapter classes that implement the Integrable interface, provide default implementations to the respective abstract methods of your choice. 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.

Upvotes: 0

Thiyagu
Thiyagu

Reputation: 17890

I would say that that the parameter of Sum must take an Integrable in that case.

You can create two classes - Sum and IntegrableSum (uhh.. need a better name)

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

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

Upvotes: 1

Related Questions