java - Use different methods based on parameter from constructor -


i have class should have different method implementations based on parameter pass class constructor. however, select implementation run @ time of object creation, , not testing specified parameter. of sort:

public class someclass(){     int parameter=-1;      someclass(int param){         this.parameter = param;     }      public methodspecific(){ //for when parameter==1;         stuff...     }      public methodspecific(){ //for when parameter==2;         stuff...     } } 

instead of:

public class someclass(){     int parameter=-1;      someclass(int param){         this.parameter = param;     }      public methodforall(){          switch(parameter){             case 1:                 something...              case 2:                 else...         }     } } 

is there way can achieve this?

edit: edit clarify situation , context. please consider figure bellow. rectangles of same color mean implementation of methods same. rectangles different colors means though name same implementation differs. need find way implement classa , classb, without duplicated code, , still allow class "main" know both classa , classb have same method names , variables.

ilustrative figure

i first thought, straightforward not wanted implementation have 2 sub classes of someclass, clarification want. still edited example comply both new , old version of question ;-)

the idea hide different implementations set of anonymous classes implement abstract methods of common base class. base class known , called runmethod1() , runmethod2() , implementation used decided @ construction time of someclass.

example:

public class someclass() {     private abstract class basicstuff     {         // code same in implementations go here         void method1() { /* same */ }          // code shall different in implementations go here         abstract void method2();     }      private final basicstuff whatshallwedotoday;      public someclass(int param)     {         switch (param)         {   // construct anonymous class functionallity of classa             case 1: whatshallwedotoday = new stuffinterface()                     {                         void method2() { /* */ }                     }                     break;              // construct anonymous class functionallity of classb             case 2: whatshallwedotoday = new stuffinterface()                     {                         void method2() { /* else */ }                     }                     break;              default:throw illegalargumentexception();         }     }      public runmethod1()     {          whatshallwedotoday.method1();     }      public runmethod2()     {          whatshallwedotoday.method2();     } } 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -