java - Overloaded Constructor calling other constructors based on input type -


say have 2 constructors taking type of input. (t1 , t2 in example)

i want call either of them more general constructor taking object (or superclass of t1 , t2 matter)

class test{     public test(t1 input){...}     public test(t2 input){...}      public test(object input){         if(input instanceof t1)             this((t1) input);         if(input instanceof t2)             this((t2) input); } 

the third constructor give compile error since this constructor call isn't on first line.

you can use kind of factory method follows:

public class test {     private test(t1 input) {         // ...     }      private test(t2 input) {         // ...     }      public static test createtest(object input) {        if (input instanceof t1)           return new test((t1) input);        if (input instanceof t2)           return new test((t2) input);         return null;     } } 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -