3

How to call the callback function of outter class without using a helper variable like i did in my example below.

Please note that the solution described in Calling outer class function from inner class probably won't work.

public abstract class Job {
    public void callback();
}

public abstract class ExtendedJob extends Job {

    protected void handleResult() {
        // workaround for accessing the outter class
        final ExtendedJob outter = this;

        new ExtendedJob {
            public void callback() {
                // can i do the same without the outter variable?
                outter.callback();
            }
        }
    }
}
Community
  • 1
  • 1
fholzer
  • 340
  • 3
  • 13
  • I dont think you can do without the variable, but its not like using the helper variable will be harmful. – DirkyJerky May 28 '14 at 16:25
  • @DirkyJerky it works, look at first answer :) – pL4Gu33 May 28 '14 at 16:27
  • How is this different from this except you have an extra extends means it has visibility to all members ? http://stackoverflow.com/questions/9043170/java-calling-outer-class-method-in-anonymous-inner-class – Abs May 28 '14 at 16:34
  • I was thinking that, as the inner class is an ExtendedJob as well, `ExtendedJob.this` would be equivalent to just `this`. But i guess the inner class actually is only a subclass of ExtendedJob. – fholzer May 28 '14 at 16:39

1 Answers1

3

I think this should do the trick

ExtendedJob.this.callback();
ciamej
  • 6,918
  • 2
  • 29
  • 39
  • 3
    No, that syntax is backwards: it's `ExtendedJob.this.callback()`. – Daniel Pryden May 28 '14 at 16:26
  • @Daniel Thanks, I was just starting eclipse to check which version is correct ;) – ciamej May 28 '14 at 16:27
  • I should've tried it myself instead of just thinking that there's no way it would work. I though it won't work because the inner class is also an ExtendedJob class. I guess it's actually a child class of ExtendedJob, anonymous, but child nevertheless. – fholzer May 28 '14 at 16:37
  • @tkSimon I guess you've confused `ExtendedJob.this.foo()` with `super.foo()` or something similar. That's actually strange that you can only call direct superclass' methods, but not methods of arbitrary class in the inheritance chain. – ciamej May 28 '14 at 16:42