1

I have a superclass with some generic behavior for downloading stuff called MySuperclass. This class has a callback interface for further use of the payload.

public class MySuperclass {

    public interface MyDownloadListener{
        void onDownload(Object payload);
    }

    private MyDownloadListener listener;
    ...

    public void download(){
        ...
        listener.onDownloaded(response);
    }

}

I derive multiple classes from MySuperclass, here called MySubclassA and MySubclassB.

public class MySubclassA extends MySuperclass{
    ...
}

public class MySubclassB extends MySuperclass{
    ...
}

The conflict occurs when I try to use both subclasses in a third class. I would have to do something like

public class MyClass implements MySubclassA.MyDownloadListener, MySubclassB.MyDownloadListener{
    ...
    public void onDownloaded(Object payload){
        // here is the conflict
    }

}

but this doesn't work because I can't distinguish between the two different callback interfaces. How can I solve this?

kaolick
  • 4,817
  • 5
  • 42
  • 53
  • On first glance, I'd make two inner classes each implementing one of the Callback interfaces and not have the (outer) class itself implement them. – Fildor Aug 25 '15 at 10:17
  • @Fildor On first glance that won't work in my case. – kaolick Aug 25 '15 at 10:20
  • possible duplicate of [Method name collision in interface implementation - Java](http://stackoverflow.com/questions/2598009/method-name-collision-in-interface-implementation-java) – Fildor Aug 25 '15 at 10:26
  • Can you tell us why it won't work in your case? – Fildor Aug 25 '15 at 10:26
  • @Fildor At second glance, I think I understand what you're suggesting. I need to take a closer look at this. But still this seems inconvenient. One might think that my problem could be quite common in `Java`. – kaolick Aug 25 '15 at 10:38

1 Answers1

1

The quickest solution: Provide a sender object which calls your callback interface:

public interface MyDownloadListener{
   void onDownload(Object payload, Object sender);
}

In your super class:

public class MySuperclass {
   ...
   public void download(){
      listener.onDownload(response, this);
   }
}

In your listener object:

public class MyClass implements MySubclassA.MyDownloadListener, MySubclassB.MyDownloadListener{
    ...
    public void onDownload(Object payload, Object sender){
        if(sender instanceof MySubclassA){
            ...
        }
        if(sender instanceof MySubclassB){
            ...
        }
    }
}
Olli Zi
  • 325
  • 2
  • 10