java - Is it possible to re-direct an instance from a constructor in a multi-class? -



checking boolean condition passed multi-class' constructor, , if true i'm trying assign this instance of sub-class.

doesn't work of course, there way re-direct instance in way? if there no way this, reasons why?


here multi-class:

public class multiclass {      string str;      public multiclass(boolean flag) {         if (flag) {              // doesn't work! wish would:             // = new extraclass();          } else {             this.str = "you in first class";         }     } } // end of multiclass  class extraclass {      string str;      extraclass() {         this.str = "you in second class";     } } // end of extraclass 


...and tester class:

public class multiclasstest {      public static void main(string[] args) {         multiclass test = new multiclass(false);         system.out.println(test.str);     } } // end of multiclasstest 


you can have either use factory method e.g. static method can return implementation create different implementations, or use delegation delegate actual implementation. (the constructed class wrapper)

note: constructor doesn't create instance, initialises instance has been created you. can't change it's type once created.


a simpler approach have 1 class checks flag determine should do. (with if statement in code)

public class multiclass {     final string str;      public multiclass(boolean flag) {         if (flag) {             this.str = "you in second class";         } else {             this.str = "you in first class";         }     } } 

Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -