Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a different constructor conditionally in Java?

Let's say someone gives you a class, Super, with the following constructors:

public class Super
{
    public Super();
    public Super(int arg);
    public Super(String arg);
    public Super(int[] arg);
}

And let's say you want to create a subclass Derived. How do you conditionally call a constructor in Super?

In other words, what is the "proper" way to make something like this work?

public class Derived extends Super
{
    public Derived(int arg)
    {
        if (some_condition_1)
            super();
        else if (some_condition_2)
            super("Hi!");
        else if (some_condition_3)
            super(new int[] { 5 });
        else
            super(arg);
    }
}
like image 496
user541686 Avatar asked Feb 10 '12 23:02

user541686


People also ask

Can we call constructor from another constructor in java?

Constructor Calling form another Constructor The calling of the constructor can be done in two ways: By using this() keyword: It is used when we want to call the current class constructor within the same class. By using super() keyword: It is used when we want to call the superclass constructor from the base class.

Can you have 2 constructor with different names?

No. It is not possible.

Can I have an if statement inside a constructor?

putting if/else statements inside of both the constructor and setters are valid often used. It ensures that the object is never in an invalid state.

Can we call private constructor if yes then how?

Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.


2 Answers

Use static factories, and four private constructors.

class Foo {
 public static Foo makeFoo(arguments) {
    if (whatever) {
      return new Foo(args1);
    } else if (something else) {
      return new Foo(args2);
    }
    etc...
  }
  private Foo(constructor1) { 
    ...
  }
  ...
}
like image 199
Louis Wasserman Avatar answered Sep 18 '22 15:09

Louis Wasserman


Yeah, what @Johan Sjöberg said.

Also looks like your example is highly contrived. There's no magical answer which would clear this mess :)

Usually, if you have such a bunch of constructors it would be a good idea to refactor them as four separate classes (a class should be only responsible for one type of thing).

like image 25
JHollanti Avatar answered Sep 18 '22 15:09

JHollanti