Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a java method return value depending upon condition?

I have a ICoreClient interface and AClient and BClient classes implements this.

ICoreClient is exposed for users.

I need to add a new method in ICoreClient interface. So, it needs to be implemented in both clients. I can not make this method generic as it has completely different signature but similar functionalities.

I have 2 interfaces xx and yy

ClientA implements xx and ClientB implements yy

So, I decided to add a new testMethod in ICoreClient that will provide me the instance of xx or yy depending upon clients.

I want to return the instance of these interfaces from a single method depending upon condition.

In ClientA:

public xx testMethod(){
  return instanceof xx;
}

In ClientB:

public yy testMethod(){
  return instanceof yy;
}

What should I write in ICoreClient interface?

public zz testMethod()

I tried putting a dummy interface zz (acting as a common supertype) both xx and yy are implementing this. But still not able to expose methods of xx and yy in their respective clients as finally it got typecasted in zz.

Is there any known approach for this kind of scenario?

Edit: If I make return type Object, method of these interfaces are not exposed. Although, Object contains the instance of xx or yy,

User still needs to cast it to (xx or yy how will user know?) for using the methods in the interface.. I want to expose the methods of the ClientX without having to cast to ClientA or ClientB...

like image 237
Dev Avatar asked Jun 03 '15 07:06

Dev


2 Answers

After your edit it looks like you may be looking for generics. You can make your interface like this

interface ICoreClient<T>{// T will be set by each class implementing this interface
    T testMethod();
}

and each of your classes can look like

class ClientA implements ICoreClient<xx>{
    xx testMethod(){
        //return xx
    }
}

class ClientB implements ICoreClient<yy>{
    yy testMethod(){
        //return yy
    }
}
like image 198
Pshemo Avatar answered Nov 01 '22 01:11

Pshemo


It is possible only if xx and yy have a common super type (interface or class). At the worst case, you can always return Object.

public Object testMethod () // or a more specific common super type of `xx` and `yy`
{    
    if (..some condition..) {
        return ..instanceof `xx`..;
    } else if (..other condition..) {
        return ..instanceof `yy`..;
    }
    return null; // or some other default instnace
}
like image 40
Eran Avatar answered Nov 01 '22 02:11

Eran