lennartVH01
lennartVH01

Reputation: 208

Overloaded Constructor calling other constructors based on input type

Say I have two constructors taking some type of input. (T1 and T2 in this example)

I want to call either of them from a more general constructor taking an Object (or any superclass of T1 and T2 for that 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 would give a compile error since the this constructor call isn't on the first line.

Upvotes: 2

Views: 169

Answers (3)

Yourim Yi
Yourim Yi

Reputation: 198

instanceof is necessary? when T1 is superclass of T2.

class T1 { }
class T2 extends T1 { }

class Test {
  public Test(T1 input) { ... }
  public Test(T2 input) {
    this((T1)input); // T2 extends T1.
    // or
    if(input instanceof T1) { this((T1)input); }
    ...
  }
}

Upvotes: 0

ujulu
ujulu

Reputation: 3309

You can use a kind of factory method as 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;
    }
}

Upvotes: 3

tfosra
tfosra

Reputation: 581

Instead of writting three constructors, just write one constructor (the one with Object parameter) and transform the two others into private methods. Now call it like this:

class Test{
    private void initT1(T1 input){...}
    private void initT2(T2 input){...}

    public Test(Object input){
        if(input instanceof T1)
            initT1((T1) input);
        else if(input instanceof T2)
            initT2((T2) input);
    }
}

Upvotes: 2

Related Questions