theomega
theomega

Reputation: 32041

Refer to enclosing class' this from anonymous inner class

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?

Upvotes: 3

Views: 111

Answers (2)

John Ericksen
John Ericksen

Reputation: 11113

You could add a second private method to avoid the naming collision:

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

Upvotes: 1

Mad Physicist
Mad Physicist

Reputation: 114330

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

Upvotes: 7

Related Questions