0

Is it possible to have an anonymous inner class return a value for a method it is contained in? For example, I want to do some calculations in something(), which is an anonymous inner class, and have doStuff() return that value.

private int doStuff(){

    Foo foo = new Foo(new Bar.Example() {
            @Override
            public void something() {
                ...
                //return int for doStuff()
            }
    });

}
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
Fouroh3
  • 542
  • 2
  • 10
  • 27
  • 3
    You can simply invoke a method on the anonymous class, e.g. `new Bar.DoStuff() { ... }.something()`. But please put a bit of effort into making your example code make sense, e.g. missing `new`, returning an `int` from a `void` method, making it clear what you're going to do to `foo` to get the value from that... – Andy Turner Apr 15 '19 at 09:01
  • Thanks for that answer! I fixed the missing `new`, but the `return 1` was me trying to indicate that I wanted `doStuff` to return 1, not have void method return 1, I did tidy it up, however. – Fouroh3 Apr 15 '19 at 09:22

1 Answers1

0

Create an Instance final variable inside doStuff() method and assign the value inside the anonymous class.

Barefooter
  • 61
  • 6
  • You can't *re-assign* a final 'variable'. Do you mean final reference? – Nicholas K Apr 15 '19 at 09:43
  • Yes, I meant to create a final reference variable like `int final value;` outside and to assign the value in the anonymous class like `value=1;` – Barefooter Apr 15 '19 at 13:22
  • That won't compile. Try it and see for yourself. Like I said earlier you can't reassign a final variable. Also your comment is ambiguous, you say reference variable but you are using a primitive. – Nicholas K Apr 15 '19 at 14:18