generics - Java - Return different child classes based on input parameters -


given these classes:

public class versionvov1 extends basevo {      private string fieldone = null;      public string getfieldone() {         return fieldone;     }     public void setfieldone(string fieldone) {         this.fieldone = fieldone; }  public class versionvov2 extends basevo {      private string fieldfour = null;      public string getfieldfour() {         return fieldfour;     }     public void setfieldfour(string fieldfour) {         this.fieldfour = fieldfour;     }  }  public class basevo {     // common code here  } 

i have calling method dosomething returns specific child class based upon input string:

public basevo dosomething(string version) {      basevo versionvo =  dosomethingversioned(createversionvo(version));      return versionvo; } 

the remaining methods are:

private basevo createversionvo(string version) {      basevo versionvo = null;      if (version.equalsignorecase("v1")) {          versionvo = new versionvov1();      } else if (version.equalsignorecase("v2"))          versionvo = new versionvov2();      return versionvo; }  protected versionvov1 dosomethingversioned(versionvov1 versionvo) throws exception {      versionvo.setfieldone("the versionvo of type: " + versionvo.getclass());     versionvo.setfieldtwo("field two");     versionvo.setfieldthree("field three");      return versionvo;  }  protected versionvov2 dosomethingversioned(versionvov2 versionvo) throws exception {      versionvo.setfieldone("the versionvo of type: " + versionvo.getclass());     versionvo.setfieldthree("field three");     versionvo.setfieldfour("field four");      return versionvo;  } 

as can see i've overridden dosomethingversioned take in specific child class. problem lies compilation error looks on dosomethingversioned: the method dosomethingversioned(versionvov1) in type versionexample not applicable arguments (basevo).

i've tried returning type of <t extends basevo> createversionvo other compilation errors in method stating type mismatch: cannot convert versionvov1 t.

i feel should easier i'm making it. how can keep overall pattern allow compile?

thanks helps!

what want pattern factory method. note: there no benefit genericity here. merely creating presumption go on way. generics tend yield greatest benefit when wanting leverage code orthogonal domain objects, e.g. collections.


Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -