2

Where do you place instance of anonymous class?

public class MyClass {
    // Variables
    private Api api;

    // Functions
    public void callApi() {
        api.get(<...>, responseListener)
    }

    // Where to put that? Top of the file, bottom, next to function?
    private ResponseListener responseListener = new ResponseListener() {
        @Override
        public void onSuccess(Object response) {
        }
    };
}

And also, in that case, would it be preferable to instantiate directly in the api call?

    public void callApi() {
        api.get(<...>, new ResponseListener() {
            @Override
            public void onSuccess(Object response) {
            }
        });
    }
mbmc
  • 5,024
  • 5
  • 25
  • 53
  • In your second version you are creating new instance of `ResponseListener` each time you invoke `callApi`. In first version you are reusing already created instance. – Pshemo Jul 20 '15 at 20:45
  • The first snippet declares an instance variable, and initializes it with an instance of an anonymous inner class. I would put it with all the other instance variable declarations: at the top of the class. – JB Nizet Jul 20 '15 at 21:09

1 Answers1

1

That's a decision that you get to make. The way you wrote it originally, you have a field called responseListener that gets initialized once and reused on each callApi() invocation. If that's the behavior you want, you could put it above the callApi() method (with the other field, api). Or leave it where it is. They're both ok, it's just which do you prefer.

If, however, you want a new instance each time callApi() is invoked, then it would make sense to put it inside callApi().

So it matters whether you put it inside callApi() or outside, but only you can decide which is better. And if you want it outside, it doesn't matter where outside, and again only you can decide which is better.

Erick G. Hagstrom
  • 4,873
  • 1
  • 24
  • 38
  • 1
    I couldn't find many recent [documents](http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141855.html#1852) about variable placement. But in case of anonymous class, it seems to be based on coder's need and/or preference. – mbmc Jul 21 '15 at 15:36