Refer to the environment class "this is from an anonymous inner class

Suppose you received the following code:

public abstract class DecisionFunctionJ {
    public abstract double evaluate();

    public DecisionFunctionJ add(final DecisionFunctionJ another) {
        return new DecisionFunctionJ() {
            @Override
            public double evaluate() {
                return this.evaluate() + another.evaluate();
            }
        };
    }
}

This code does not work as intended because it leads to an infinite circle / StackOverflowException. The reason for this is obvious: it this.evaluate()refers to the method of the evaluateinternal anonymous class, and not to the method of the evaluateexternal abstract class.

How can I execute an external method evaluate? Using DecisionFunctionJ.this.evaluate()does not help, because both classes are of type DecitionFunctionJ.

What are the other features?

+3
source share
2 answers

You can use the link DecisionFunctionJ.thisto refer to the class class:

public abstract class DecisionFunctionJ {
    public abstract double evaluate();

    public DecisionFunctionJ add(final DecisionFunctionJ another) {
        return new DecisionFunctionJ() {
            @Override
            public double evaluate() {
                return DecisionFunctionJ.this.evaluate() + another.evaluate();
            }
        };
    }
}
+7
source

, :

public abstract class DecisionFunctionJ {
    public abstract double evaluate();

    public DecisionFunctionJ add(final DecisionFunctionJ another) {
        return new DecisionFunctionJ() {
            @Override
            public double evaluate() {
                return outerEvaluate() + another.evaluate();
            }
        };
    }

    private double outerEvaluate(){
        return evaluate();
    }
}
+1

All Articles