3

In the sample code below, I have an interface inside class so that I'm using the methods of interface. But i don't see any effect with/without interface methods. Can someone help me what is the purpose of adding including them?

public class Controller {

    FlowerCallBackReceiver mListener;

    @Override
    public void success(String s, Response response) {
        try { 
            mListener.onFetchProgress(flower);
        } catch (JSONException e) {
            mListener.onFetchFailed();
        }
        mListener.onFetchComplete();
    }

    @Override
    public void failure(RetrofitError error) {
        mListener.onFetchComplete();
    }

    public interface FlowerCallBackReceiver {
        void onFetchProgress(Flower flower);
        void onFetchComplete();
        void onFetchFailed();
    }
}
Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
Ravi
  • 631
  • 5
  • 15
  • 2
    Can you clean up your code? You have a dangling catch with no try, a random `});` floating on its own etc. – Michael May 16 '17 at 20:05
  • Please compile the code that you plan to post. It should either compile clean, or raise the exact error you expect. – Lew Bloch May 16 '17 at 20:52
  • @Michael .My intention was to raise question regarding purpose of inner interface inside class so that i added edited code to make it short. There might be some piece of code missing. – Ravi May 16 '17 at 20:56

2 Answers2

2

This nested interface declaration is just a simple organizational technique. It won't change the standard Java interface semantics at all.

For instance, developers use it to clean up the top level package namespace. It's a matter a style, one may say.

Some quick Java SE examples:

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
  • 1
    You may also want to have a look at these two other SO questions: http://stackoverflow.com/questions/16648642/why-should-we-declare-an-interface-inside-a-class and http://stackoverflow.com/questions/36530066/interface-inside-class – GMax May 16 '17 at 20:03
  • @GMax Good catch! – Paulo Mattos May 16 '17 at 20:06
0

There is no obvious reason to have that interface there, based on the code you have shown.

One might typically nest an interface inside a class if implementations of that class are to be used in the body of the rest of the class, for example if Controller had a method like:

void doSomething(FlowerCallBackReceiver callback) {
  // ...
}

But this interface isn't used here, so it's not apparent why it would be here.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243