Refer to enclosing class' this from anonymous inner class

java

Solution

You can use the `DecisionFunctionJ.this` reference to reference the enclosing 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();
            }
        };
    }
}

Problem

Supposing you got 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 intented because it leads into an endlessloop / `StackOverflowException`. The reason for this is clear: the `this.evaluate()` references the `evaluate` method of the inner anonymous class and not the `evaluate` method of the outer abstract class. How can I execute the outer `evaluate` method? Using `DecisionFunctionJ.this.evaluate()` does not help because both classes are of type `DecitionFunctionJ`. What are the other possibilities?

Original source