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
Post a Comment