Ahmad Siavashi
Ahmad Siavashi

Reputation: 999

How an Interface passed to a class can call a method from that class?

Suppose I have the following interface

public interface I {
    public int evaluate();
}

and the following class

public class A {
    // ...
    public int getX(){}
    public int evaluateX(I model){
        return model.evaluate();
    }
}

then, can I have an implementation of I such that

class Model implements I {
    @Override
    public int evaluate() {
        return getX() + 1;
    }
}

in which the implementation is calling a method of class A?

I know of Reflection but I would like to know about a static technique.
Thank you

Upvotes: 0

Views: 72

Answers (2)

tsolakp
tsolakp

Reputation: 5948

Why not use lmbdas? Looks like your example is a good candidate for it.

public interface I {
    public int evaluate( Supplier<Integer> s);
}

public static class A {

    public int getX(){return 5;}

    public int evaluateX(I model){

        return model.evaluate( () -> getX() );
    }
}

public static class Model implements I {

    @Override
    public int evaluate(Supplier<Integer> s) {
        return s.get() + 1;
    }
}

Upvotes: 1

Mena
Mena

Reputation: 48404

The simple answer is no.

Also, this would look like tight coupling, as the interface would have to know about the classes it's being injected into.

What you may want to do is parametrize the evaluate method and its implementations with an int, so you could pass it as getX() when invoking in class A, then increment by 1 in your Model class's evaluate implementation.

Edit

As suggested by Andy Thomas, you may want to furtherly generalize.

Instead of parametrize evaluate with an int, you could parametrize it with an interface declaring the int getX() method (which A would subsequently implement).

In turn, A would invoke model.evaluate(this), and Model's evaluate implementation would change into something like return myGivenArgument.getX() + 1.

Up to you to decide whether this is necessary based on the context.

Upvotes: 3

Related Questions