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);
}
}
解决方案
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).