Timmiej93 Timmiej93 - 5 months ago 21
Android Question

Is there an alternative to overloading methods in an Interface?

I am using an

Interface
for a
CallBack
(both of which I'm very new to). Until now, all my
CallBacks
have been of the same element type, but now I want to return a different element type.

Current situation:

public interface CallBack {
void CallBack(String s)
}


What I thought would work:

public interface CallBack {
void CallBack(String s)
void CallBack(Integer i)
}


This (obviously for most of you) tells me I have to implement both methods when using the
CallBack
, which is not my intended use.

I know I could 'fix' this for now by changing it to
void CallBack(Object o)
, but I don't like the ambiguous type and would like to make it more solid.

Is there any way I can make this so my
CallBack
Override
looks like this:

...new CallBack() {
@Override
public void CallBack(String s) {
...


... or ...

...new CallBack() {
@Override
public void CallBack(Integer i) {
...


... instead of having to implement both, or using the
Object
variant?

Answer

You can use generic interface as below

public interface CallBack<T> {
    T CallBack(T s);
}

and use it as follow

new CallBack<String>() {

            @Override
            public String CallBack(String s) {
                // TODO Auto-generated method stub
                return null;
            }

        };

or

new CallBack<Integer>() {

            @Override
            public Integer CallBack(Integer s) {
                // TODO Auto-generated method stub
                return null;
            }


        };